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.
const val MAX_USERS = 100 fun main() { println("The maximum number of users is $MAX_USERS") }
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 valis 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.const val improves performance by replacing variables with actual values.val is for runtime constants, const val is for compile-time.