scala 的可变和不可变设置何时使用 val 和 var [英] scala's mutable and immutable set when to use val and var

查看:54
本文介绍了scala 的可变和不可变设置何时使用 val 和 var的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 Scala Creator 的 Programming in Scala 一书,但我对 Set 的示例有些困惑.

I'm reading the Programming in Scala book by the Scala Creator and I'm a bit confuse on the example of Set.

这里是不可变集:

var jetSet = Set("Boeing", "Airbus")
jetSet += "Lear"
println(jetSet.contains("Cessna"))

这有什么意义?

集合是不可变的,但变量 jetSet 是可变的.1) 所以每次我用 += 添加到集合时,它都会创建一个新集合?所以变量指向内存中的一个新集合?

The set is immutable but the variable jetSet is mutable. 1) So every time I add to the set with += it creates a new set? So the variable point to a new set in memory?

2) 不应该是:val jetSet = set("cow","sheep","duck") ?为什么它必须是一个var?是否有理由将 var 用于不可变集合?

2) Shouldn't it be: val jetSet = set("cow","sheep","duck") ? Why does it have to be a var? Is there a reason to use var for a immutable set?

推荐答案

不可变数据结构(在本例中为 Set)的优点是它们是持久的.例如:

The advantage of immutable data structures, in this case Set, is that they are persistent. For example:

var jetSet1 = Set("Boeing", "Airbus")
val jetSet2 = jetSet1 // ... imagine jetSet2 is somewhere else in the program
jetSet1 += "Lear"
assert(!jetSet2.contains("Lear"))

这些 Set 对象的不变性使得程序更容易推理,因为对 jetSet1 变量的更新不会对代码的其他部分产生副作用(在这种情况下,无论 使用 jetSet2).虽然从这个例子中并不清楚,但有时在可变的 var 引用中存储不可变的值是很方便的;大多数情况下,var 的作用域是有限的(例如,局部于函数).

Immutability of these Set objects makes it easier to reason about the program because updates to the jetSet1 variable don't have side effects in other parts of the code (in this case, wherever jetSet2 is used). Although it's not clear from this example, there are occasions when it's convenient to store immutable values in mutable var references; most often, the var will have a limited scope (e.g., local to a function).

不可变数据结构通常具有非常高效的巧妙实现.不幸的是,Scala 集合 API 没有关于性能的详细记录,但我预计大多数操作的时间大约为 O(log N).例如,给定一个大的不可变集合 s,应该能够有效地构造 s + x,一个带有额外元素的新集合.当然,不变性保证了 s 也被保留了下来.在幕后,ss+x 将使用某种具有共享组件的树数据结构进行存储.

Immutable data structures often have clever implementations that are quite efficient. Unfortunately, the Scala collection API is not well documented regarding performance, but I would expect most operations to be roughly O(log N) time. For example, given a large immutable Set s, one should be able to efficiently construct s + x, a new Set with an extra element. Of course, immutability guarantees that s is also preserved. Under the hood, s and s+x will be stored using some kind of tree data-structures with shared components.

您的问题标题表明您也在寻找有关使用 valvar 的建议.经验法则是在方便的时候使用 val.如果 var 是必要的,那么尽量限制变量的范围.

The title of your question suggest you are also looking for advice about using val or var. The rule of thumb is to use val whenever you can conveniently. If a var is necessary, then try to limit the variable's scope as much as possible.

这篇关于scala 的可变和不可变设置何时使用 val 和 var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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