我理解事物的方式是“变量”一词指的是重新分配引用的能力。 “常量”意味着不能重新分配引用。本质上是 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() 而无需重新分配给新标识符。
是我误解了什么,还是用词不当?
最佳答案
There are two keywords to declare a variable:
val
(from value)—Immutable reference. A variable declared withval
can’t be reassigned after it’s initialized. It corresponds to afinal
variable in Java.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/