I wonder why there is no equivalent keyword in Kotlin like C++ const or Swift mutable func. I think it is missing another keyword in kotlin that does not allowed to call setter on const/val data. It’s weird to read in a code :
val list = ...
list += 5
The +=
operator should not be authorized for val
data. Maybe we need something like:
val readOnly = mutableListOf(1, 2, 3, 4)
val readOnly += 5 // Forbidden call of plusAssign because of mutability
mutable val mutableList = listOf(1, 2, 3, 4)
mutableList += 5 // Allowed due to the mutable keyword
The mutable keyword indicates that we allowed to change the inner state of the object.
It could works with objects Interfaces if we have:
interface MutableList<T> {
mutable operator fun plusAssign(value: T) = TODO("Do stuff")
}
Here we can know if a mutable val or a simple val can call the method. It may also works with custom classes and interface. All val objects should not call mutable marked properties or functions when mutable objects may call its mutable fields or functions.
With this there is not needs to write to interfaces for each collections with Mutability/Non mutability specification and for the call we may use the keyword before the arguments like:
fun foo(mutable list: List<T>) // we may modify the list but not the inner objects
fun foo(mutable list: List<mutable T>) // we may modify the list and the inner objects
fun foo(list: List<mutable T>) // we may modify the inner objects but not the list
fun foo(list: List<T>) // we cannot modify the list
The key word will create a fictive hierarchy as:
val t: T
mutable val t: T // is in fact Mutable<T> : T
class Child: T
val c: Child // c inherits from T
mutable val c1: Child // c is Mutable<C> and inherits with covariance
Why do you think about it ?