Scala 集合中的可变与不可变 [英] mutable vs. immutable in Scala collections

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

问题描述

我对 Scala 相当陌生,正在尝试了解集合层次结构.我看到可变"和不可变"集合之间存在区别,但我不明白这在实现级别实际上意味着什么以及这与 valvar.谁能给我一些这方面的见解?此外,是否每个集合类都有一个可变"版本和一个不可变"版本,或者是否有一些类只能是可变"或不可变"?

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'?

推荐答案

可变意味着您可以就地更改集合.所以,如果你有一个集合 c 并且你附加了一个带有 += 的元素,那么 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.

Immutable 意味着集合对象永远不会改变;相反,您可以使用诸如 +++ 之类的操作构建新的集合对象,这些操作返回一个新集合.这在并发算法中很有用,因为它不需要锁定来向集合添加内容.它可能会以一些开销为代价,但此属性可能非常有用.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.

区别与 varval 之间的区别非常相似,但请注意:

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

  1. 您可以就地修改绑定到 val 的可变集合,但不能重新分配 val
  2. 你不能就地修改一个不可变的集合,但是如果它被分配给一个 var,你可以将该 var 重新分配给一个由它构建的集合+等操作.
  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.

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

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