Why Bother, When We Have val?

val is immutable, but the value might not be determined until runtime:

import kotlin.random.Random

val randomNumber = Random.nextInt(1, 100)

Here, we do not know what the value of randomNumber is until this property is initalized. We cannot change the value of randomNumber, but we do not know the value at compile time.

By contrast, const creates a compile-time constant.

Some bits of code need compile-time constants. The biggest one is annotations. An annotation property needs to be a compile-time constant, since the annotation itself might be applied at the time the code is compiled.

Also, the Kotlin compiler may be able to perform additional optimizations for compile-time constants, since the value is known to the compiler, compared to simple immutable val values.

So, for things that can be a constant, using const has some value, though usually it is not essential.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.