Hi,
There is basically 2 types of immutability; Referential immutability and Immutable values. Referential immutability refers to the reference being immutable and not the object itself.
In the following example:
“val mutableList”
The mutableList reference is immutable because of “val”. This means you if you instantiate it like this:
“val mutableList = mutableListOf(1,2,3,4)“,
You cannot reassign it like this:
“mutableList = mutableListOf(5,6,7,8)“.
However, you would still be able to mutate the list assigned to “mutableList” like this:
“mutableList.add(10)”
This is known as Referential immutability.
On the other hand, with:
“var immutableList = listOf(1,2,3,4)“,
You would be able to reassign the object bound to the variable “immutableList”. Therefore, you would be able to do things like this:
“var immutableList = listOf(1,2,3,4)
immutableList = listOf(5,6,7,8)”
However, you would not be able to mutate the object itself like this:
“immutableList.add(10)”
This type of immutability is known as Immutable values.
So to answer your question, if you need to mutate properties within an object but not the object itself, stick with “val”, and if you need to assign new objects to the same variable and not mutate properties within that variable, then use “var” (As an aside, I honestly cannot think of a use case where this would be necessary).
Obviously you can go down the road of “var mutableList”, but with that you lose all the benefits of immutability 🙂
I hope you find that helpful.
Reference: Functional Kotlin (Chapter 3)