案例类copy()方法抽象 [英] Case class copy() method abstraction
问题描述
我想知道是否可以抽象case类的复制方法。基本上我有一些像 sealed trait Op
,然后像 case类Push(值:Int)extends Op
第一个问题:没有参数/成员的case类没有定义一个复制方法。您可以在REPL中尝试此操作。
scala> case类Foo()
定义类Foo
scala> Foo()。copy()
< console>:8:错误:值副本不是Foo的成员
Foo()。copy()
^
scala> case类Foo(x:Int)
定义类Foo
scala> Foo(0).copy()
res1:Foo = Foo(0)
有一个原因为什么编译器做这个异常?我认为这是相当的直观,我希望每个 case类定义一个复制方法。
第二个问题:我有一个方法 def ops:List [Op]
并且我想复制所有ops如 ops map {_.copy()}
。如何在 Op
trait中定义复制方法?如果我说 def copy():Op
,我得到一个太多参数错误。然而,由于所有copy()方法只有可选参数:为什么这不正确?而且,我该怎么做呢?通过使用另一个名为 def clone():Op
的方法,并写入所有位置 def clone案例类?我希望不会。
- 编译器生成的复制方法对case类有什么好处没有任何参数?
- 至 quote Lukas Rytz (我相信他实现了它):
如果类中没有名为复制的成员,则直接定义或继承。
I would like to know if it is possible to abstract the copy method of case classes. Basically I have something like sealed trait Op
and then something like case class Push(value: Int) extends Op
and case class Pop() extends Op
.
The first problem: A case class without arguments/members does not define a copy method. You can try this in the 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)
Is there a reason why the compiler makes this exception? I think it is rather unituitive and I would expect every case class to define a copy method.
The second problem: I have a method def ops: List[Op]
and I would like to copy all ops like ops map { _.copy() }
. How would I define the copy method in the Op
trait? I get a "too many arguments" error if I say def copy(): Op
. However, since all copy() methods have only optional arguments: why is this incorrect? And, how do I do that correct? By making another method named def clone(): Op
and write everywhere def clone() = copy()
for all the case classes? I hope not.
- What would be the benefit of a compiler generated copy method for case classes without any arguments? This would just return a new Foo, and not copy anything.
- To quote Lukas Rytz (I believe he implemented it):
The copy methods are only generated if there is no member named"copy" in the class, directly defined or inherited.
这篇关于案例类copy()方法抽象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!