default case class argument depending on other arguments scala

424 views Asked by At

In scala I'm not allowed to perform the following:

case class Terminal(value: Double, name: String = value.toString)

Moreover I also cannot do this:

case class Terminal(value: Double)(name: String = value.toString)

I understand the multiple parameter list approach is not supported for constructors.

Is is there a way to define in the apply method in order to make this possible?

Expected behavior:

Terminal(1.0) // => Terminal (1.0, "1.0")
2

There are 2 answers

0
HTNW On BEST ANSWER

You can't do this in the case class itself, and it won't make a constructor, but it is possible through the apply method on the companion.

case class Terminal(value: Double, name: String)
object Terminal {
  def apply(value: Double): Terminal = Terminal(value, value.toString)
}

Note that:

def apply(value: Double, name: String = value.toString) = new Terminal(value, name)

is an error because it conflicts with the autogenerated apply.

0
Cortwave On

Maybe you just want this?

case class Terminal(value: Double) {
    val name = a.toString
}