6
votes

I'm evaluating Scala and am having a problem with its immutable collections.

I want to make immutable collections, which are completely immutable, right down through all the contained objects, the objects they reference, ad infinitum.

Is there a simple way to do this?

The code on http://www.finalcog.com/immutable-containers-scala illustrates what I'm trying to achieve, and a nasty work around (ImmutablePoint).

The problem with the workaround is that every time I want to change an object I have to manually make a new copy. I understand that the runtime will have to implement copy-on-write, but can this be made transparent to the developer?

I suppose I'm looking to make Immutable Objects, where methods change the current object state, but all other 'val' (and all immutable container) references to the object retain the 'old' state.

2
This paper might interest you: lamp.epfl.ch/~phaller/capabilities.htmlMitch Blevins
Excellent reading material, thanks.fadedbee

2 Answers

9
votes

This is not possible out-of-the-box with scala via some specific language construct unless you have followed the idiom that all of your objects are immutable, in which case this behaviour comes for free!

With 2.8, named parameters have made "copy constructors" quite nice to use, from a readability perspective. But you are correct, this works as copy-on-write. The behaviour you are asking for, where the "current" object is the only one mutated goes completely against the way the JVM works, unfortunately (for you)!

Actually the phrase "the current object" makes no sense; really you mean "the current reference"! All other references (outside the current lexical scope) which point to the same object, erm, point to the same object! There is only one object!

Hence it's just not possible for this object to appear to be mutable from the perspective of the current lexical scope but immutable for others

2
votes

If you're interested in some more general theory on how to handle updates to immutable data structures efficiently,

http://en.wikipedia.org/wiki/Zipper_%28data_structure%29

might prove interesting.