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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With