简体   繁体   English

在不不断复制构造函数 vals 的情况下扩展 Scala 案例类?

[英]Extending scala case class without constantly duplicating constructors vals?

Is there a way to extend a case class without constantly picking up new vals along the way?有没有一种方法可以扩展案例类,而无需在此过程中不断获取新的 vals?

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 . "a" conflicts with "a" ,所以我不得不重命名为a1 But I don't want all kinds of extra public copies of "a" so I made it private.但我不想要“a”的各种额外公共副本,所以我将其设为私有。

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?这对我来说似乎并不干净......我错过了什么吗?

As the previous commenter mentioned: case class extension should be avoided but you could convert your Edge class into a trait.正如之前的评论者所提到的:应该避免案例类扩展,但您可以将 Edge 类转换为特征。

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不要忘记在特征中更喜欢def而不是val

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您没有多余的val ,并且
  • you have 2 case classes.你有 2 个案例类。

Case classes can't be extended via subclassing.不能通过子类扩展案例类。 Or rather, the sub-class of a case class cannot be a case class itself.或者更确切地说,案例类的子类不能是案例类本身。

Starting in Scala 3 , traits can have parameters :Scala 3开始, 特征可以有参数

trait Edge(a: Strl, b: Strl)
case class EdgeQA(a: Strl, b: Strl, c: Int, d: Int) extends Edge(a, b)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM