I’m relatively new to Kotlin, and I’ve already rewritten big portions of production code to it because it’s a really awesome language. As of now, I’d only miss a recursive immutability modifier, like
const in c++.
There’s a small discusson on that in the slack’s #language-proposals channel, and thanks to some contributions (mostly arguments against my proposal) I’ve been able to develop it better, so I’ll give it a try here.
That modifier would be able to target
- Methods/functions: to tell they are read-only. In the scope of such methods, all members are treated like vals so they can’t be set, and only their read-only methods can be called.
- Variables: to identify them as immutable. Right now we have val to tell the reference cannot change, but the value is not readonly and you can perfectly mute the object it points to. By having that modifier we would not be able to call any setter nor any non-readonly function
Real immutability is a pretty important feature, Kotlin itself already has had to implement it for containers (with my proposal containers would be able to go back to having only 1 implementation handling both mutable and immutable references)
But there’s a catch in here: with only that (which would already be a pretty awesome language feature for a better typing and restrictions), we cannot assert that a immutable object will not be modified in another thread that has a mutable reference to it. In my opinion that’s not a good enough reason, but we could still do something about it in runtime.
Every object could have an atomic flag stack telling whether it’s in readonly state or not.
When an object becomes referenced as immutable, that flag would be pushed, and when leaving that reference’s scope it would be popped.
Then, whenever a mutating operation is performed on an object with that flag set, an exception would be thrown.
This could be optimized to have pretty much no overhead, but still it would be nice if it’s only enabled with a runtime flag.
What do you think about it?
EDIT: The compiler should be able to detect by itself when a method is readonly or not, so the method modifier could be just a hint for the compiler to throw an error when a method has that modifier but it’s mutating the object.
EDIT 2: With all that in mind, we could have a new concept: immutable classes. These would not need any locks whatsoever because they would be immutable by definition. We could have an
immutable class modifier which asserts that for any class. Clear example: