在不不断复制构造函数 val 的情况下扩展 Scala 案例类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11165432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extending scala case class without constantly duplicating constructors vals?
提问by LaloInDublin
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. But I don't want all kinds of extra public copies of "a" so I made it private.
"a" conflicts with "a",所以我被迫重命名为a1. 但是我不想要“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?
这对我来说似乎不干净......我错过了什么吗?
回答by bajohns
As the previous commenter mentioned: case class extension should be avoided but you could convert your Edge class into a trait.
正如前面的评论者所提到的:应该避免 case 类扩展,但您可以将 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 defover valin traits
不要忘了喜欢def过val的特质
回答by david.perez
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.
- 你没有多余的
vals,并且 - 你有 2 个案例类。
回答by nickgroenke
Case classes can't be extended via subclassing. Or rather, the sub-class of a case class cannot be a case class itself.
案例类不能通过子类化来扩展。或者更确切地说,案例类的子类不能是案例类本身。
回答by Xavier Guihot
Note that with Dotty(foundation of Scala 3), traits can have parameters:
请注意,使用Dotty(的基础Scala 3),特征可以具有参数:
trait Edge(a: Strl, b: Strl)
case class EdgeQA(a: Strl, b: Strl, c: Int, d: Int) extends Edge(a, b)

![scala 如果 Int 不能为 null,null.asInstanceOf[Int] 是什么意思?](/res/img/loading.gif)