加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

关于Scala变量可变性的问题

发布时间:2020-12-16 18:19:32 所属栏目:安全 来源:网络整理
导读:据我所知,val关键字确定底层变量是一个Immutable类型(以后不能重新分配).现在我在 scala编程中遇到了一个段落(第3章,scala中的后续步骤 – 使用类型参数化数组),它说明 val greetStrings: Array[String] = new Array[String](3)greetStrings(0) = "Hello"gre
据我所知,val关键字确定底层变量是一个Immutable类型(以后不能重新分配).现在我在 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,
but the object to which it refers
could potentially still be changed.

但如果我宣布这样的话

val str = "immutable string"

根据书中给出的定义

它所指的对象在上面的代码行中可能仍然可以改变它的含义?

解决方法

声明val不保证甚至暗示不可变类型.它只声明你可能在Java中调用的最终变量.不能重新分配标识符,但该值可以是可变类型.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读