With emphasis on immutability in a programming language like Scala (avoid "var"), does this mean that the "state change methods" in my object will have to return a copy of the instance (with a new state)?
Let's look at the turtle. I would like to move my turtle like this:
val turtle = new Turtle(0, 0, "north") val turtle2 = turtle.turnLeft().forward(5).turnRight().backward(2)
Here turtle2 will not point to the same Turtle instance (these are two separate instances). In fact, 4 temporary objects were created in this sequence of movements. Here is how I could implement the turnLeft method, for example:
def turnLeft { self.copy(orientation = self.orientation match { case "north" => "west" case "east" => "north" case "south" => "east" case "west" => "south" }) }
Is this the right design approach?
If so, how effective / inefficient (creating a new object with every method call)? If not, what will be right? What is wrong or missing in my understanding of the aspect of immutability (or, possibly, functional programming in general)?
Thanks in advance, Raka
source share