You can provide an additional apply method in the companion object that computes some parameters of the case class:
case class TestClass(param1 : String, param2 : String)
object TestClass {
def apply(param1: String): TestClass =
TestClass(param1, s"The value of param1 is : $param1")
}
You can use either apply method:
scala> TestClass("foo")
res0: TestClass = TestClass(foo,The value of param1 is : foo)
scala> TestClass("foo", "bar")
res1: TestClass = TestClass(foo,bar)
Note, that while it's possible to move param2 to a second parameter list or inside the class definition:
case class TestClass(param1: String)(param2: String = s"The value of param1 is : $param1")
// Here it's also harder to override the value of `param2`, if needed.
case class TestClass(param1: String) {
val param2: String = s"The value of param1 is : $param1"
}
this changes the semantics of the generated unapply, equals, hashCode and most importantly copy methods, so in many cases this is not a viable solution.
param2should be a method or public variable insidecase class TestClass(param1: String) {val param2 = ... }