I got some difficulties designing my case classes. A simplified version looks like:
abstract class Base(s: Option[String]) {
//code
}
case class CaseClass(s: Option[String] = None) extends Base(s) {
//code
}
And I have a method where I want to do something like:
def method(base : Base) = {
//code
base copy (s = Some("string"))
}
Of course I get:
value copy is not a member of Base
So what I want to do is create a new instance based on my base class (which is not a case class). Obviously one can not do this. But how would you solve this in a elegant way?
Thanks in advance!
The behavior you’re trying to achieve is not implementable.
copymethod of a case class is autogenerated by the compiler, and once you add a method calledcopyto your implementation, compiler will not generate any sugar.You can reimplement
copywith traits, but it will not be as flexible as the generated one (you will have to update the base trait,copyandmethodimplementations every time the field-set of a case class changes):Alternatively, you can implement
methodas follows:Thus you won’t need
Basetrait, and reduce the number of alterations, if your case classes change.