I am trying to model my class hierarchy in case classes. I appreciate related discussion about duplication of case class properties here.
Consider the class hierarchy shown below.
trait Super {
def a:String
}
case class Child1(a:String, b:String) extends Super {
override def toString = s" a = $a, b= $b"
}
case class Child2(a:String, c:String) extends Super {
override def toString = s" a = $a, c= $c"
}
I have a scenario where I want to construct case class objects using basic properties like a
, b
, c
as well as using XML. I created companion objects for these case classes as below.
object Child1 {
def apply(node: scala.xml.Node): Child1 = {
val a = (node \ "a").text
val b = (node \ "b").text
Child1(a, b)
}
}
object Child2 {
def apply(node: scala.xml.Node): Child2 = {
val a = (node \ "a").text
val c = (node \ "c").text
Child2(a, c)
}
}
In above code, I have to duplicate the line that parses value of a
- (node \ "a").text
. There doesn't seem to be a way to do the same even if I convert Super
to an abstract
superclass.
I wonder how one can do this, which I could have done very easily using abstract class and couple of constructors in Super
class in Java.
UPDATE: Qualified name for scala.xml.Node type.