dmitry
dmitry

Reputation: 5049

Scala class constructor default arguments with expression using previous members

I'd want to create a class (or better case class) which would behave like this:

case class MyClass(n: Int, m: Int = 2 * n)

So that m could have default value based on n. But seems it is impossible, scala says: not found: value n. First idea is to write m: Int = -1 and mutate it in constructor if it's still -1, but it is val. And now I have no any other ideas.

Maybe anybody will shed some light on what's possible here?

Upvotes: 3

Views: 348

Answers (2)

twillouer
twillouer

Reputation: 1178

You must define a companion object :

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

case class MyClass(n: Int, m: Int);

object MyClass {
def apply(n: Int) : MyClass = new MyClass(n, n * 2)
}

// Exiting paste mode, now interpreting.

defined class MyClass
defined module MyClass

scala> MyClass(12);
res4: MyClass = MyClass(12,24)

Upvotes: 0

Régis Jean-Gilles
Régis Jean-Gilles

Reputation: 32729

You can explicitly provide a second factory:

case class MyClass(n: Int, m: Int)
object MyClass{
  def apply(n: Int): MyClass = MyClass(n, 2 * n)
}

Unlike when using 2 parameter lists as in @om-nom-nom's answer, the case class is unaffected, and in particular you can pattern match as usual to extract both n and m.

Upvotes: 3

Related Questions