Let’s start off by introducing val.
To define a variable in Kotlin, you may use var or val:
| var | val |
|---|---|
| has a mutable value (changeable) | has an immutable value (read-only) |
So we use val for immutable values, so what is the const keyword and what’s its difference from val?
| const | val |
|---|---|
| has an immutable value (read-only) | has an immutable value (read-only) |
| initialized at compile time only | value may be assigned during runtime |
Other rules for const in Kotlin:
- must be a top-level property or placed within a companion object
- value must be a primitive type (can never have function or any class constructor as its value)
- no custom getter