我想知道是否可以抽象案例类的复制方法。基本上我有类似 sealed trait Op
的东西然后像 case class Push(value: Int) extends Op
和 case class Pop() extends Op
.
第一个问题:没有参数/成员的案例类没有定义复制方法。您可以在 REPL 中尝试此操作。
scala> case class Foo()
defined class Foo
scala> Foo().copy()
<console>:8: error: value copy is not a member of Foo
Foo().copy()
^
scala> case class Foo(x: Int)
defined class Foo
scala> Foo(0).copy()
res1: Foo = Foo(0)
编译器是否有原因导致此异常?我认为它相当统一,我希望每个案例类都定义一个复制方法。
第二个问题:我有一个方法
def ops: List[Op]
我想复制所有操作,如 ops map { _.copy() }
.我将如何在 Op
中定义复制方法特质?如果我说 def copy(): Op
,我会收到“参数过多”错误.但是,由于所有 copy() 方法都只有可选参数:为什么这是不正确的?而且,我该如何正确地做到这一点?通过创建另一个名为 def clone(): Op
的方法到处写 def clone() = copy()
对于所有案例类?我希望不会。
最佳答案
The copy methods are only generated if there is no member named"copy" in the class, directly defined or inherited.
关于scala - 案例类 copy() 方法抽象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2911562/