Scala 中的 val-mutable 与 var-immutable [英] val-mutable versus var-immutable in Scala

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

问题描述

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.

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

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