Updating value of node in Scala?

271 Views Asked by At

I have this code

tree match {
            case EmptyNode => 
                //do stuff with empty node
            case Node(left, right, value) =>
                //do stuff with node contents 
}

However what if I want to update the value of a node? I tried doing value = newValue inside the case, but it doesn't seem to be allowed.

Structure of my trees/nodes:

sealed trait Tree
case class Node(var left: Tree, var right: Tree, var value: String) extends Tree
case object EmptyNode extends Tree
2

There are 2 best solutions below

0
On BEST ANSWER

You can reference the actual node with @ notation:

case n@Node(left, right, value) => n.value = "newValue"
1
On

Noah's answer does show the way to change the value of the node, but you shouldn't do that. One of the main ideas of scala is to promote immutable data structures, i.e. once you define an object, you don't change it.

This is particularly important in a tree, because by changing the value of the node, you are potentially making your tree inconsistent (values to the left of the node may no longer be smaller). Instead, always keep nodes values immutable and add or delete nodes as needed, minding rebalancing of the tree when a node is deleted.