java - Kotlin 术语 "mutable"错了吗?

标签 java android kotlin variables constants

我理解事物的方式是“变量”一词指的是重新分配引用的能力。 “常量”意味着不能重新分配引用。本质上是 Java 中 final 与 not 的区别。

var something = new obj() -> reference can be re-assigned  
val something = new obj() -> cannot be re-assigned

对我来说,“可变性”意味着修改 REFERAND/OBJECT 本身的能力,而不是它的引用。 IE。 引用的对象。但 Kotlin 并没有阻止这一点。

你可以拥有

val something = new obj()

但仍然能够“变异”该 obj() 而无需重新分配给新标识符。

是我误解了什么,还是用词不当?

最佳答案

valvar只控制引用的不变性,而不是它指向的对象。

来自 Kotlin in Action

There are two keywords to declare a variable:

  1. val (from value)—Immutable reference. A variable declared with val can’t be reassigned after it’s initialized. It corresponds to a final variable in Java.
  2. var (from variable)—Mutable reference. The value of such a variable can be changed. This declaration corresponds to a regular (non-final) Java variable.

Note that, even though a val reference is itself immutable and can’t be changed, the object that it points to may be mutable. For example, this code is perfectly valid:

val languages = arrayListOf("Java")
languages.add("Kotlin")

关于java - Kotlin 术语 "mutable"错了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69217287/

相关文章:

android - 模块依赖于一个或多个 Android 库,但在使用 VS 2017 构建 Cordova 应用程序时出现 Jar 错误

java - 为什么 RxJava Observable.doOnDispose 会触发两次?

java - 格式标志转换不匹配异常

java - 使用 for 循环获取字符串中的最后一个单词?

java - java子类的私有(private)final字段可以在 super 构造函数完成之前初始化吗?

android - Flutter - 使用带有 android 多种风格的 faSTLane

java - 将 HttpClient 3 和 4 放在同一个类路径中是否安全?

android - 在推送通知事件中维护父 Activity

kotlin - ArraysJVM.kt VS _ArraysJVM.kt

Kotlin 从 JSON 获取值(value)