Reputation: 365
I have this tree structure
sealed trait Tree
case class Node(var left: Tree, var right: Tree, var value: String) extends Tree
case object EmptyNode extends Tree
and a Tree object called myTree. I want to make another tree with the exact same structure and values called otherTree, but myTree.clone() does not work. What else can I do?
Upvotes: 0
Views: 1652
Reputation: 341
Just for completeness - as the question asks for 'How to copy...' and you mentioned clone(): You can copy case classes with the copy() method. Yet it won't help with a tree structure that is mutable. But with an immutable structure (as Gregor suggests above), e.g. like this
sealed trait Tree
case class Node(left: Tree, right: Tree, value: String) extends Tree
case object EmptyNode extends Tree { override def toString = " _ " }
and some data
scala> val leaf1 = Node(EmptyNode, EmptyNode, "leaf1")
scala> val leaf2 = Node(EmptyNode, EmptyNode, "leaf2")
scala> val tree1 = Node(leaf1, leaf2, "tree1")
scala> tree1
res0: Node = Node(Node( _ , _ ,leaf1),Node( _ , _ ,leaf2),tree1)
you can copy your tree like this
scala> val tree2 = tree1.copy(value = "tree2")
tree2: Node = Node(Node( _ , _ ,leaf1),Node( _ , _ ,leaf2),tree2)
or
scala> val tree3 = Node(tree1.left, tree1.right, "tree3")
tree3: Node = Node(Node( _ , _ ,leaf1),Node( _ , _ ,leaf2),tree3)
As usual with immutable instances, for updates you would need to create new tree structures for example using recursive operations as in Noah's answer.
Upvotes: 0
Reputation: 13959
Something like this will copy your Tree
:
def copyTree(t:Tree):Tree = {
t match {
case EmptyNode => EmptyNode
case Node(left, right, value) => Node(copyTree(left), copyTree(right), value)
}
}
Upvotes: 4