对象中的可变值 [英] Mutable values in an object
问题描述
在Scala中,如果我计划有一个可变属性(例如一个数字包)的对象,什么时候适合
In Scala, if I'm planning on having a mutable attribute (e.g. a bag of numbers) of an object, when is it appropriate to
- 创建var并使用不可变的数据结构?
- 创建val并使用可变数据结构?
我会猜测你想使用#2作为线程应用程序吗?有些集合是线程安全的吗?
I'm going to throw a guess out that you'd want to use #2 for threaded applications? Are some of the collections thread-safe?
一般来说呢? (或者它真的没有关系吗?)
How about in general? (Or does it not really matter?)
推荐答案
在你的选择1和2之间,无关紧要 - ,如果从多个线程读取或修改值,则需要同步对属性的访问,无论属性本身是不可变数据的 var
结构或可变数据结构的 val
。这两种选择都不会自动同步。
Between your choices 1 and 2, it doesn't matter - mutable is mutable, and if you read or modify the value from multiple threads, you'll need to synchronize access to the property, no matter if the property itself is a var
of an immutable data structure or a val
of a mutable data structure. Neither choice will give you automatic synchronization.
这篇关于对象中的可变值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!