Immutability in Type-C
Type-C enforces mutability through slightly unconventional ways.
Immutability
Type-C doesn't enforce value immutability, but rather reference immutability.
This is because you can still safely use x after z is changed, since the change of z doesn't affect x.
However, if x is an object, then it's a different story.
Since x is declared as const, it cannot be assigned to a non-const variable.
Immutability is inherited. Meaning, if a variable is declared as const, all its properties are also const.
So now we have established that:
- Immutability protects the reference (and sub references), not the value.
- Immutability is inherited.
- Immutability must be maintained when assigning to a new variable.
Function Arguments Mutability
In Type-C, Function arguments are immutable by default.
To make this work, you need to declare the argument as mutable.
If you dare and call this function with a const argument, you will get an error.
Class Attributes Mutability
Class attributes can be declared as const to make them immutable. This immutability is disabled when the class is being initialized, i.e within the init function.
If you are desperate to mutate a const attribute, mutate keyword can be used.
General Mutability Heads Up
- Whenever you construct an expression using a const variable, the result is also const
- a = [x, y, z] the expression [x, y, z] is considered constant if any of x, y, or z is constant.
- a = {x: x1, y: y1} the expression {x: x1, y: y1} is considered constant if any of x1 or y1 is constant.
- Variadic arguments are mutable only if the variant is mutable.
- A class attribute mutability is also influenced by the instance mutability OR(attribute is const, instance is const)
How to adapt to Type-C immutability
Embrace them! Type-C immutability is designed to make your code safer and more predictable. It's a feature, not a bug. Use it to your advantage. Avoid mutate whenever you can, as it signifies:
- You are too lazy to refactor your code
- You have no idea what you are doing
- You are performing some optimizations and you really know what you are doing, in that case, you have my blessing.