1

I want to set the default value of a parameter of a case class using its own parameters that were declared previously. Something like:

case class TestClass(param1 : String, param2 : String = s"The value of param1 is : $param1")

This, however, throws an error stating the variables are not defined. Can anyone suggest how I can accomplish this or any alternate ways forward?

1
  • param2 should be a method or public variable inside case class TestClass(param1: String) {val param2 = ... } Commented May 15, 2018 at 16:31

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.