Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala class constructor default arguments with expression using previous members

Tags:

syntax

scala

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?

like image 970
dmitry Avatar asked Feb 11 '26 21:02

dmitry


1 Answers

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.

like image 165
Régis Jean-Gilles Avatar answered Feb 13 '26 14:02

Régis Jean-Gilles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!