如何复制案例类对象?

时间:2017-03-06 16:02:52

标签: scala tree

这就是我试过的

 sealed abstract class Tree
case class NewNode(left: Tree,center: Tree, right: Tree) extends Tree

我只想复制整个对象

scala> val treeM = treeD.copy_
<console>:16: error: value copy_ is not a member of NewNode
       val treeM = treeD.copy_
                     ^

以上不起作用

scala> val treeM = treeD.copy(_,_,_)
treeM: (Tree, Tree, Tree) => NewNode = <function3>

scala> println("Tree M == Tree D: %s" format (treeM == treeD).toString)
<console>:18: warning: (Tree, Tree, Tree) => NewNode and NewNode are unrelated: they will most likely never compare equal
       println("Tree M == Tree D: %s" format (treeM == treeD).toString)

如何编写正确的对象副本?

2 个答案:

答案 0 :(得分:1)

不带任何参数调用copy

val treeM = treeD.copy()

答案 1 :(得分:1)

您可以,但没有理由复制不可变对象。