Immutability
If the state of an object can't be changed after it is initialized, then we consider this object immutable. Immutability allows you to write simple and reliable code. If the state of an object can't be changed, we can safely use it as a key for a map
function, as in the following example:
fun main(vars: Array<String>) { data class ImmutableKey(val name: String? = null) val map = HashMap<ImmutableKey, Int>() map[ImmutableKey("someName")] = 2 print(map[ImmutableKey("someName")]) }
We can consider the ImmutableKey
class immutable because all its variables are marked with the val
keyword and are initialized using a primary constructor.
Another significant thing about this example is that the ImmutableKey
class is marked with the data
modifier.
Data classes
Let's decompile our ImmutableKey
to Java. The first lines look as follows:
final class ImmutableKey { @Nullable private final String name; @Nullable public final String getName() { return this.name; } public ImmutableKey...