Scala default arguments of class constructor with expression using previous members

I want to create a class (or better case class) that will behave like this:

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

      

So it m

can have a default based on n

. But it seems that this is not possible, the scala says not found: value n

. The first idea is to write m: Int = -1

and mutate in the constructor if it's still -1, but it is val

. And now I have no other ideas.

Can anyone shed some light on what's possible here?

+3


source to share


2 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 using 2 parameter lists as in @ om-nom-nom's answer, the case class is unaffected, and in particular, you can match the pattern as usual to extract both n

and m

.

+3


source


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)

      

0


source







All Articles