0
0
KotlinConceptBeginner · 3 min read

What is const val in Kotlin: Explanation and Examples

const val in Kotlin declares a compile-time constant value. It means the value is fixed and known when the program is compiled, making it faster and safer to use than regular variables.
⚙️

How It Works

Think of const val as a label on a box that never changes. Once you set the value, it stays the same forever, and the program knows this value even before it runs. This is different from regular variables that can change while the program is running.

Because const val values are fixed at compile time, Kotlin replaces every use of that constant with the actual value in the code. This makes the program faster and safer because the value cannot accidentally change.

💻

Example

This example shows how to declare and use a const val in Kotlin.

kotlin
const val MAX_USERS = 100

fun main() {
    println("The maximum number of users is $MAX_USERS")
}
Output
The maximum number of users is 100
🎯

When to Use

Use const val when you have a value that should never change and is known before the program runs, like configuration values, fixed limits, or constant strings.

For example, you might use const val for API keys, fixed URLs, or mathematical constants like Pi. This helps keep your code clear and efficient.

Key Points

  • const val is for compile-time constants only.
  • It must be a top-level or inside an object or companion object.
  • Only primitive types and String are allowed.
  • It improves performance by inlining values.

Key Takeaways

const val declares a fixed value known at compile time.
Use it for constants like fixed numbers or strings that never change.
const val improves performance by replacing variables with actual values.
It can only be used with primitive types and Strings at top-level or in objects.
Regular val is for runtime constants, const val is for compile-time.