How to make Scala immutable collections contain immutable objects

I appreciate Scala and I have a problem with its immutable collections.

I want to make immutable collections that are completely immutable, down to all contained objects, the objects that they reference, to infinity.

Is there an easy way to do this?

The code http://www.finalcog.com/immutable-containers-scala illustrates what I am trying to achieve and the nasty work (ImmutablePoint).

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

I suppose I want to make Immutable Objects, where the methods change the current state of the object, but all the other "val" references (and all immutable containers) to the object retain the "old" state.

+6
immutability scala functional-programming scala-collections
source share
2 answers

This is not possible because of the box with scala through any particular language construct if you did not follow the idiom that all your objects are immutable, in which case this behavior is provided free of charge!

Since 2.8, named parameters have made copy constructors pretty enjoyable in terms of readability. But you're right, it works like copy-on-write. The behavior you are asking about where the "current" object is the only mutated one is completely contrary to how the JVM works, unfortunately (for you)!

Actually, the phrase "current object" does not make sense; in fact, you mean "current link "! All other links (outside the current lexical area) that point to the same object, erm, point to the same object! There is only one object !

Therefore, it is simply not possible for this object to look mutable in terms of the current lexical domain, but unchanged for others.

+9
source share

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

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

may be interesting.

+2
source share

All Articles