有关Scala变量可变性的问题 [英] Question about Scala variable Mutability

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

问题描述

我知道 val 关键字确定基础变量是不可变类型(以后无法重新分配).现在,我遇到了Scala编程中的一个段落(第3章,Scala的后续步骤-使用类型对数组进行参数化),它指出

I understand that val keyword determines the underlying variable is a Immutable type (Cannot be reassigned later time). Now i come across a paragraph in programming in scala (Chapter 3, Next steps in scala - parameterize arrays with types), it states

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

这三行代码说明了 要理解的重要概念 关于Scala的含义 瓦尔当您定义一个变量 val,该变量无法重新分配, 但是它所指的对象 可能仍会更改.所以 在这种情况下,您无法重新分配 greetStrings到另一个数组; greetStrings将始终指向 与之相同的Array [String]实例 它已初始化.但是你可以改变 该Array [String]的元素 随着时间的流逝,数组本身就是 易变.

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.

因此更改数组的元素有效.如果我们这样定义,它就无效

so its valid to change the elements of array. And its invalid if we define like this

greetStrings = Array("a","b","c")

满足以下条件

使用以下命令定义变量时 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.

但是如果我声明这样的话

but if i declare something like this

val str = "immutable string"

根据书中给出的定义

在上面的代码行中,所引用的对象可能仍会更改?

推荐答案

声明 val 不能保证甚至暗示不可变的类型.它仅将您在Java中可能称为 final 的变量声明为变量.不能重新分配标识符,但是该值可以是可变类型.

Declaring a val does not guarantee or even imply an immutable type. It only declares what you might call in Java a final variable. The identifier cannot be re-assigned, but the value may be of a mutable type.

在字符串值的示例中,您同时具有 val 和不可变类型String.因此,该标识符既不可重新分配也不可修改(不变).

In your example of a string value, you have both a val and an immutable type, String. So this identifier is neither re-assignable nor modifiable (immutable).

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

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