val-mutable对var-immutable在Scala [英] val-mutable versus var-immutable in Scala

查看:131
本文介绍了val-mutable对var-immutable在Scala的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Scala中有什么指导,何时使用可变集合的val,而不是使用var不可变集合?或者你应该真正瞄准val和一个不可变的集合吗?

Are there any guidelines in Scala on when to use val with a mutable collection versus using var with an immutable collection? Or should you really aim for val with an immutable collection?

事实上,这两种类型的集合给了我很多选择,通常我不
知道如何做出这个选择。

The fact that there are both types of collection gives me a lot of choice, and often I don't know how to make that choice.

推荐答案

很常见的问题,这一个。困难的是找到重复的。

Pretty common question, this one. The hard thing is finding the duplicates.

您应该努力获得参照透明度。这意味着,如果我有一个表达式e,我可以做一个 val x = e ,并替换 e x 。这是可变性打破的属性。

You should strive for referential transparency. What that means is that, if I have an expression "e", I could make a val x = e, and replace e with x. This is the property that mutability break. Whenever you need to make a design decision, maximize for referential transparency.

实际上,方法局部 var 是最安全的 var ,因为它不会转义方法。如果方法很短,甚至更好。如果不是,请尝试通过提取其他方法来减少它。

As a practical matter, a method-local var is the safest var that exists, since it doesn't escape the method. If the method is short, even better. If it isn't, try to reduce it by extracting other methods.

另一方面,可变集合具有潜在 ,即使它不。当更改代码时,您可能需要将其传递给其他方法,或返回它。

On the other hand, a mutable collection has the potential to escape, even if it doesn't. When changing code, you might then want to pass it to other methods, or return it. That's the kind of thing that breaks referential transparency.

在对象(字段)上,发生了几乎相同的事情,但会产生更严重的后果。无论哪种方式,对象将具有状态,因此,中断参考透明度。但是具有可变的集合意味着即使对象本身可能失去对谁改变它的控制。

On an object (a field), pretty much the same thing happens, but with more dire consequences. Either way the object will have state and, therefore, break referential transparency. But having a mutable collection means even the object itself might lose control of who's changing it.

这篇关于val-mutable对var-immutable在Scala的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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