17

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)
                                       ^

2 Answers 2

25

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!!
Sign up to request clarification or add additional context in comments.

2 Comments

Nice answer. That's quite a gotcha when using case classes, and it's still not fixed as of 2.11.6.
Actually, I consider it a useful feature to be able define parameters that do not participate in equality and hash.
10

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)

4 Comments

I find this method more useful, but I'm giving 0__'s answer the acceptance, because it seems to be more popular.
Actually, the green check is supposed to mean what solved your problem, however you define that. But I would guess you solved your problem a couple of years ago.
Yeah, in retrospect, I don't know why I switched the green checks.
Took a second look after all these years. This is definitely the better solution! Giving back the green check!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.