mutable vs. immutable在Scala集合 [英] mutable vs. immutable in Scala collections

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

问题描述

我对于Scala非常陌生,我试图理解集合层次结构。我看到'mutable'和'immutable'集合之间有区别,但是我不明白这在实现级别是什么意思,以及这与 val var 。谁能给我一些洞察这一点?此外,每个集合类都有一个mutable版本和一个immutable版本,还是有一些类只能是mutable或immutable?

I am fairly new to Scala and am trying to understand the collections hierarchy. I see that there is a distinction between 'mutable' and 'immutable' collections, but I don't understand what this actually means at the implementation level and how this relates to val and var. Can anyone give me some insight on this? Also, does every collection class have a 'mutable' version and an 'immutable' version, or are there some classes which can only be 'mutable' or 'immutable'?

推荐答案

Mutable意味着您可以就地更改集合。所以,如果你有一个集合 c ,并且添加一个 + = 的元素,那么

Mutable means you can alter the collection in-place. So, if you have a collection c and you append an element with +=, then c has changed, and so has every other reference to that collection.

不可改变意味着集合对象永远不会改变;而是使用 + ++ 等操作创建新的集合对象,其中返回新集合。这在并发算法中非常有用,因为它不需要锁定即可向集合添加内容。它可能以一些开销为代价,但这个属性可能非常有用。 Scala的不可变集合是完全持久的数据结构

Immutable means that the collection object never changes; instead, you build new collection objects with operations such as + or ++, which return a new collection. This is useful in concurrent algorithms, since it requires no locking to add something to a collection. It may come at the cost of some overhead, but this property can be very useful. Scala's immutable collections are fully persistent data structures.

差异非常类似于 var val 之间,但要注意:

The difference is very similar to that between var and val, but mind you:


  1. 您可以修改绑定到 val 的可变收集,但不能重新分配 val

  2. 您不能在位修改不可变集合,但如果分配给 var ,您可以将 var 重新分配到通过 + 等操作从中构建的集合。 li>
  1. You can modify a mutable collection bound to a val in-place, though you can't reassign the val
  2. you can't modify an immutable collection in-place, but if it's assigned to a var, you can reassign that var to a collection built from it by an operation such as +.

并非所有集合都必须存在于可变和不可变变体中;上次我检查,只支持可变优先级队列。

Not all collections necessarily exist in mutable and immutable variants; the last time I checked, only mutable priority queues were supported.

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

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