scala - 关于Scala变量可变性的问题

标签 scala immutability

我明白 val 关键字确定底层变量是不可变类型(以后不能重新分配)。现在我在 scala 编程中遇到了一个段落(第 3 章,scala 的下一步 - 使用类型参数化数组),它指出

val greetStrings: Array[String] = new Array[String](3)
greetStrings(0) = "Hello"
greetStrings(1) = ", "
greetStrings(2) = "world!\n"

These three lines of code illustrate an important concept to understand about Scala concerning the meaning of val. When you define a variable with val, the variable can’t be reassigned, but the object to which it refers could potentially still be changed. So in this case, you couldn’t reassign greetStrings to a different array; greetStrings will always point to the same Array[String] instance with which it was initialized. But you can change the elements of that Array[String] over time, so the array itself is mutable.



所以改变数组的元素是有效的。如果我们这样定义它是无效的
greetStrings = Array("a","b","c")

它满足下面的陈述

When you define a variable with val, the variable can’t be reassigned, but the object to which it refers could potentially still be changed.



但如果我声明这样的事情
val str = "immutable string"

根据书中给出的定义

这是什么意思它所指的对象仍有可能被更改 在上面的代码行中??

最佳答案

声明 val 不保证甚至暗示不可变类型。它只声明您可能在 Java 中调用的内容 最后 多变的。标识符不能重新分配,但值可能是可变类型。

在您的字符串值示例中,您同时拥有 val 和一个不可变类型,String。所以这个标识符既不可重新分配也不可修改(不可变)。

关于scala - 关于Scala变量可变性的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3342077/

相关文章:

Scala Iterator.takeWhile 正在删除失败的元素

python - 在Python中的线程之间共享字典时是否可以避免锁定开销?

reference - 如何避免在 Rust 中为可变和不可变引用编写重复的访问器函数?

java - 不可变键 - Java 中的固定长度映射

regex - Scala 转义换行符和制表符

Scala 选项类型未按预期推断

Scala 设置不变性

c# - CLR 对不可变结构做了什么?

scala - 类似于 SBT 的 maven-shade 插件

scala - 如何在scala中将元组列表转换为数据框