Extending scala case class without constantly duplicating constructors vals?
This solution offers some advantages over the previous solutions:
trait BaseEdge {
def a: Strl
def b: Strl
}
case class Edge(a:Strl, b:Strl) extends BaseEdge
case class EdgeQA(a:Strl, b:Strl, right:Int, asked:Int ) extends BaseEdge
In this way:
- you don't have redundant
val
s, and - you have 2 case classes.
As the previous commenter mentioned: case class extension should be avoided but you could convert your Edge class into a trait.
If you want to avoid the private statements you can also mark the variables as override
trait Edge{
def a:Strl
def b:Strl
}
case class EdgeQA(override val a:Strl, override val b:Strl, right:Int, asked:Int ) extends Edge
Don't forget to prefer def
over val
in traits
Starting in Scala 3
, traits can have parameters:
trait Edge(a: Strl, b: Strl)
case class EdgeQA(a: Strl, b: Strl, c: Int, d: Int) extends Edge(a, b)
Case classes can't be extended via subclassing. Or rather, the sub-class of a case class cannot be a case class itself.