const
- Kotlin course
- Beginner
- Lesson 9/116
- 4 min
Learn to define compile-time constants with const val.
const
Constants declared with const val are computed at compile-time. They must be of primitive types (Int, Double, String, Boolean) and live at the top level or inside an object.
Values computed at runtime cannot be const. Writing const val PI = 3.14 replaces PI with 3.14 everywhere.
const val MAX = 100
fun main() {
println(MAX)
}Practice Declare a constant
At the top level, declare const val MAX = 100. Inside fun main(), print with println(MAX).
Sample solution
const val MAX = 100
fun main() {
println(MAX)
}Expected output
100
const vs val
The difference between const val and val is when the constant is computed. const val is computed at compile-time and replaced by its value at every use; so it can only be a constant expression.
val is computed once at runtime and holds a reference. For example, val x = readLine() is valid, but const val x = readLine() is a compile error.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is a compile-time constant?
- const val MAX = 100 Correct answer
- var y = 10
- lateinit var z
- val x = 5
Explanation: Constants declared with const val are computed at compile-time.
2 const: match the terms
| Term | Meaning |
|---|---|
const val |
Compile-time |
val |
Runtime, immutable |
var |
Mutable |
lateinit |
Deferred |
3 const: fill in the missing part
const ____ MAX = 100
const val MAX = 100
Explanation: const val defines a compile-time constant.