Nullability – val and var revisited
When we declare an instance of a class with val
it does not mean we cannot change the value held in the properties. What determines whether we can reassign the values held by the properties is whether the properties themselves are val
or var
.
When we declare an instance of a class with val
, it just means we cannot reassign another instance to it. When we want to reassign to an instance, we must declare it with var
. Here are some examples:
val someInstance = SomeClass() someInstance.someMutableProperty = 1// This was declared as var someInstance.someMutableProperty = 2// So we can change it someInstance.someImutableProperty = 1 // This was declared with val. ERROR!
In the preceding hypothetical code, an instance called someInstance
is declared, and it is of the SomeClass
type. It is declared as val
. The three lines of code that follow suggest that, if its properties were declared with var
we can change those properties, but, as we have already learned, when...