如何让Scala的不可变集合保存不可变对象 [英] How to make Scala's immutable collections hold immutable objects

查看:112
本文介绍了如何让Scala的不可变集合保存不可变对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想制作不可变的集合,它们是完全不可变的,直到所有的包含的对象,它们引用的对象,无穷无尽。



有没有简单的方法来做到这一点?



http:// www.finalcog.com/immutable-containers-scala 举例说明了我正在努力实现的目标,以及一个令人讨厌的工作(ImmutablePoint)。



问题解决方法是每次我想更改一个对象时,都必须手动创建一个新副本。我知道运行时必须实现copy-on-write,但是这对开发人员来说是否透明?



我想我正在创建不可变对象,其中方法改变当前的对象状态,但所有其他的'val'(以及所有不可变容器)对象的引用保持'旧'状态。

解决方案

通过一些特定的语言构造,scala不可能实现这种功能,除非您遵循了所有对象不可变的习惯用法,在这种情况下,行为是免费的!



2.8的命名参数使得复制构造函数非常好用,从可读性的角度来看。但是你是正确的,这是作为copy-on-write工作的。你所要求的行为,当前对象是唯一一个突变完全违背JVM工作方式的地方,不幸的是(对你而言)!

实际上短语当前对象没有意义;你的意思是当前的参考!所有其他指向同一对象的引用(在当前词法作用域之外),erm,指向同一个对象只有一个对象



因此,从当前词法范围的角度来看,这个对象看起来是不可变的,不可改变的其他人


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.

解决方案

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

这篇关于如何让Scala的不可变集合保存不可变对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆