开发者

How to make Scala's immutable collections hold immutable objects

开发者 https://www.devze.com 2022-12-19 04:55 出处:网络
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 o

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 a开发者_运维知识库round (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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消