So, It is not a global problem. But... its like a DRY problem. Lets introduce it. If I have a trait with some abstract member
trait WithSomeValue {
val someValue: Int
}
and some structure with case classes and their companions both inherited from this trait, if I have to make some static thing like a value and save it in Static(companion), like this:
object Foo extends WithSomeValue {
override val someValue: Int = 1
}
I need to assign it while implement trait in case class too
case class Foo(val x: Int) extends WithSomeValue {
override val someValue: Int = Foo.somevalue// I don`t like to write this! I feel myself DRY and tired ;)
}
What can I do? Can I do something elegant not to write this assignment again and again? To write it in one place only?
I need to have available static members in static context and I have to get an hierarchy - trait->case class both? but I don`t want to write DRY code. I hope some trick exists, to avoid code duplication.
For example you can override the member in a common parent of the case class and its companion object
What about
?
Actually, this is not a code duplication because a case class and its companion object are absolutely different classes
Class companion object vs. case class itself
someValuecan be implemented in them absolutely differently.Anyway you can use the following macro annotation (see sbt settings below). It generates the member in the companion object copying the member from a class. If the companion object doesn't exist the annotation creates it.
Slightly different implementation. The annotation generates the member in a class delegating to the member of the companion object.
Auto-Generate Companion Object for Case Class in Scala (sbt settings for macro annotations)
automatically generate case object for case class
Generate companion object for case class with methods (field = method)