can someone explain to me the difference between a reference and a referenced object?
Notice that the type of the variable reference (var, val) relates to the reference itself, not the properties of the referenced object. This means that when using a read-only reference (val), we will not be able to change the reference that is pointing to a particular object instance (we will not be able to reassign variable values), but we will still be able to modify properties of referenced objects. Let's see it in action using an array:
val list = mutableListOf("a","b","c") //1
list = mutableListOf("d", "e") //2 Error
list.remove("a") //3
- Initialize mutable list
- The compiler will throw an error because value reference cannot be changed (reassigned)
- The compiler will allow to modify content of the list The keyword val cannot guarantee that the underlying object is immutable.