Home > Software engineering >  Is the Kotlin term "mutable" wrong?
Is the Kotlin term "mutable" wrong?

Time:09-22

The way I understood things is that the word "variable" referred to the capability of a reference to be reassigned. "constant" meant a reference cannot be reassigned. Essentially the difference between final or not in Java.

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

To me "mutability" meant the ability to modify the REFERAND/OBJECT itself, not its reference. I.E. the object being referenced. But Kotlin doesn't prevent that.

You can have

val something = new obj()

but still be able to "mutate" that obj() without reassigning to a new identifier.

Am I misunderstanding something, or is this a misnomer?

CodePudding user response:

val and var only control the immutability of the reference not the object that it points to.

From 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")
  • Related