Last Updated:

Differences between val and const val in Kotlin

Take the following example:

Both of these variables are unmodified, but the second is declared with a keyword const in the beginning. What does this really mean? Firstly FANCY_VAL will become a private variable to be accessed by a getter. This can be seen if you compile the code and then decompile it in Java:

Second, the variable FANCY_CONST_VAL will be lined up, that is, the compiler will replace all the received values of this variable with the value itself. This, too, can be seen if you write code that uses these variables and then compile and decompile it.

Original code:

Decompiled code:

Inference: const val allows you to optimize the code, getting rid of unnecessary hatters and accesses to variables.