views:

240

answers:

2

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.

+7  A: 

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

oxbow_lakes
Thanks for your answer. Yes, I do mean the current reference. I think I'm being a bit woolly on what I mean by object. If I'm abstracting an accounting system, for example, an object representing an account is a single object. However the object may have gone through multiple states. I would like immutable containers to reference the object in the 'state' in which it existed at the time it was put into the container. In my workaround (using only immutable objects) the account would be represented by a series of objects sharing a common account_id field.
chrisdew
In conclusion, it looks like I'll have to use immutable objects all the way down. Thanks for your time.
chrisdew
+2  A: 

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_(data_structure)

might prove interesting.

Matt
Thanks, that is interesting. Perhaps I can walk without my imperative crutches...
chrisdew