Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

val-mutable versus var-immutable in Scala

Are there any guidelines in Scala on when to use val with a mutable collection versus using var with an immutable collection? Or should you really aim for val with an immutable collection?

The fact that there are both types of collection gives me a lot of choice, and often I don't know how to make that choice.

like image 420
James McCabe Avatar asked Jul 08 '12 20:07

James McCabe


1 Answers

Pretty common question, this one. The hard thing is finding the duplicates.

You should strive for referential transparency. What that means is that, if I have an expression "e", I could make a val x = e, and replace e with x. This is the property that mutability break. Whenever you need to make a design decision, maximize for referential transparency.

As a practical matter, a method-local var is the safest var that exists, since it doesn't escape the method. If the method is short, even better. If it isn't, try to reduce it by extracting other methods.

On the other hand, a mutable collection has the potential to escape, even if it doesn't. When changing code, you might then want to pass it to other methods, or return it. That's the kind of thing that breaks referential transparency.

On an object (a field), pretty much the same thing happens, but with more dire consequences. Either way the object will have state and, therefore, break referential transparency. But having a mutable collection means even the object itself might lose control of who's changing it.

like image 168
Daniel C. Sobral Avatar answered Oct 15 '22 14:10

Daniel C. Sobral