Dominykas Mostauskis
Dominykas Mostauskis

Reputation: 8125

How can a parameter's default value reference another parameter?

How can a parameter's default value reference another parameter? If it cannot, how to work around that?

case class A(val x:Int, val y:Int = x*2)

Error (reasonably enough):

scala> case class B(val x:Int, val y:Int = x*2)
<console>:7: error: not found: value x
   case class B(val x:Int, val y:Int = x*2)
                                       ^

Upvotes: 17

Views: 2369

Answers (2)

som-snytt
som-snytt

Reputation: 39577

Since you asked for the work-around, if it's not obvious how to preserve caseness:

scala> :pa
// Entering paste mode (ctrl-D to finish)

case class Foo(x: Int, y: Int)
object Foo {
  def apply(x: Int): Foo  = apply(x, 2*x)
}

// Exiting paste mode, now interpreting.

defined class Foo
defined object Foo

scala> Foo(5,6)
res45: Foo = Foo(5,6)

scala> Foo(5)
res46: Foo = Foo(5,10)

Upvotes: 10

0__
0__

Reputation: 67280

This requires that you use multiple parameter lists:

case class A(x: Int)(y: Int = x*2)

Default values can only refer to parameters in preceding lists.

Be careful however with case classes, because their equality only takes into the account the first parameter list, therefore:

A(1)() == A(1)(3)  // --> true!!

Upvotes: 25

Related Questions