Let’s start.

First, from the famous Kotlin/Native memory model rule “a datum is either mutable or shared”, we can infer the exact opposite rule that describes the exact same concept: “a datum is either thread local or immutable”.

Kotlin/Native proposes a freeze API that renders an object (and all its subgraph) immutable. I’ve exposed in my previous article that I think this is a very bad idea to enforce immutability at run-time. So let’s introduce the const keyword in Kotlin.

C++ has an interesting approach to this: a type annotation. In Kotlin, it would look like this:

fun description(foo: const Foo): String {}

The description function states that it will not mutate the foo object, it will only read values from it. To enforce this, the compiler would only allow the function to access const val geters and const functions, something that in Kotlin would look like:

class Foo {

const val answer = 42

const fun getName(): String = TODO()

}

Here, the getName method is essentially pure, the compiler will ensure that it does not mutate the object (has no side effect).

This const type annotation is a very bad idea in Kotlin, for a lot of reasons:

It would mean going over the entire standard library code-base to add const keyword to every pure functions such as map, filter, etc.

There would be const all over the place. The vast majority of functions and methods do not mutate data. Sure enough, the const keyword in C++ is everywhere, impairing readability.

So why not make it the opposite? Say that everything is immutable unless explicitly defined mutable. Rust does that with the mut keyword. Unfortunately, while this is very appealing to programmers that love constrains (a group in which I proudly associate myself), we are not going to change the semantic of the entire existing Kotlin code-base. This would require everybody to go over all the Kotlin code that ever was created in order to add the mut keyword everywhere it is needed.

Not going to happen.