Extending scala case class without constantly duplicating constructors vals?

ScalaInheritance

Scala Problem Overview


Is there a way to extend a case class without constantly picking up new vals along the way?

For example this doesn't work:

case class Edge(a: Strl, b: Strl)
case class EdgeQA(a: Strl, b: Strl, right: Int, asked: Int) extends Edge(a, b)

"a" conflicts with "a", so I'm forced to rename to a1. But I don't want all kinds of extra public copies of "a" so I made it private.

case class Edge(a: Strl, b: Strl)
case class EdgeQA(private val a1: Strl, private val b1: Strl, right: Int, asked: Int) extends Edge(a, b)

This just doesn't seem clean to me... Am I missing something?

Scala Solutions


Solution 1 - Scala

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

Solution 2 - Scala

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 vals, and
  • you have 2 case classes.

Solution 3 - Scala

Case classes can't be extended via subclassing. Or rather, the sub-class of a case class cannot be a case class itself.

Solution 4 - Scala

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLaloInDublinView Question on Stackoverflow
Solution 1 - ScalabajohnsView Answer on Stackoverflow
Solution 2 - Scaladavid.perezView Answer on Stackoverflow
Solution 3 - ScalanickgroenkeView Answer on Stackoverflow
Solution 4 - ScalaXavier GuihotView Answer on Stackoverflow