With the emphasis on immutability in programming language like Scala (avoid "var"), does it mean "state-modifying methods" in my object will have to return a copy of the instance (with the new state)?
Let's consider 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 wouldn't point to the same instance of Turtle (they're two separate instances). In fact, in that sequence of movements 4 interim objects were created. This is how I would implement the method turnLeft, for example:
def turnLeft { self.copy(orientation = self.orientation match { case "north" => "west" case "east" => "north" case "south" => "east" case "west" => "south" }) } Is that a correct design approach?
If yes, how efficient / inefficient is that (creation of new object on every method call)? If no, what would be the right one? What is wrong / missing in my understanding of immutability aspect (or maybe functional programming in general)?
Thanks in advance, Raka