开发者

How should I extend a case class if a derived class is meant to have the same parameter and shouldn't override?

开发者 https://www.devze.com 2023-04-12 18:22 出处:网络
case class Message(xml : Node) { def toXML : Node = xml } case class开发者_运维知识库 ReqValidationMessage (xml : Node) extends Message(xml){
case class Message(xml : Node) {
  def toXML : Node = xml
}

case class开发者_运维知识库 ReqValidationMessage (xml : Node) extends Message(xml){
  // ...
}

This causes a property naming conflict as Scala tries to create a second property named xml in ReqValidationMessage case class. But I want both constructors (of Message and ReqValidationMessage) to have the same argumentation. What should I do?


The short answer is: You should not extend a case class — case class inheritance is now deprecated.


Instead of subclassing case classes, why not use mixins to replicate common features:

trait XMLConvertible {
  def xml: Node
  def toXML = xml
}

case class Message(xml : Node) extends XMLConvertible

case class ReqValidationMessage(xml : Node) extends XMLConvertible {
  //...
}

Then if you want to use directly XMLConvertible for pattern matching add a companion object:

object XMLConvertible {
   def unapply( xc: XMLConvertible ) = Some( xc.xml )
}

Which allows you to write:

case XMLConvertible(xml) => println( xml )


If you want to stick with the scheme you presented, then you can just change the name of argument in second constructor - to something like xml2. Then you will have no naming conflict, and everything will work.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号