When working with Kotlin, you’ll often come across two keywords for defining immutable variables: const and val. While both ensure that the value cannot be reassigned, they serve different purposes and operate under distinct rules. In this guide, we’ll take an in-depth look at const vs val, their key differences, use cases, and best practices.
What is const in Kotlin?
The const keyword in Kotlin is used to declare compile-time constants. This means that the value is known and assigned at compile time, rather than at runtime.
Characteristics of const:
- Declared using
const val(notconst varsince it must be immutable). - Can only be assigned primitives (
Int,Double,Boolean,String, etc.). - Cannot be assigned a function call or any computed value.
- Must be declared at the top level, inside an
object, or within acompanion object.
Example of const Usage:
const val APP_NAME = "MyKotlinApp"
const val MAX_RETRY_COUNT = 3Here, APP_NAME and MAX_RETRY_COUNT are known at compile time and will never change throughout the application lifecycle.
Where You Can Use const
- Inside top-level declarations (outside any function or class).
- Inside an
objectorcompanion object.
Example in an object:
object Config {
const val API_ENDPOINT = "https://api.softaai.com"
}This approach ensures that constants are easily accessible and prevent unnecessary object instantiation.
What is val in Kotlin?
The val keyword is used for declaring runtime immutable variables. This means that once a val variable is assigned, it cannot be changed, but its value is determined at runtime.
Characteristics of val:
- Assigned a value at runtime, not compile-time.
- Can hold any type of object, including lists, function calls, and class instances.
- Can be declared anywhere, including inside functions.
- Cannot be reassigned, but the referenced object may be mutable, like MutableList (the content of that object can change).
Example of val Usage:
val timestamp = System.currentTimeMillis() // Assigned at runtime
val user = User("Amol Pawar") // Holding an object instanceHere, timestamp gets a value at runtime when the function executes.
Where You Can Use val
- Inside functions
- Inside classes and objects
- As local variables
- As properties of a class
Example Inside a Function:
fun fetchData() {
val currentTime = System.currentTimeMillis()
println("Data fetched at: $currentTime")
}currentTime gets assigned a value dynamically when the function runs.
Key Differences Between const and val
| Feature | const | val |
|---|---|---|
| Evaluation Time | Compile-time | Runtime |
| Allowed Data Types | Only primitives (String, Int, etc.) | Any type (objects, lists, function results, etc.) |
| Can Hold Function Calls? | No | Yes |
| Can Be Declared Inside Functions? | No | Yes |
| Where Can It Be Declared? | Top-level, object, companion object | Anywhere |
| Immutable? | Yes | Yes (but object properties may be mutable) |
When to Use const vs val?
Use const when:
- The value never changes and is known at compile time.
- You need a global constant (e.g., API keys, app configurations).
- The value is a primitive or string.
Use val when:
- The value is immutable but assigned at runtime.
- You need to store computed values like timestamps or function results.
- You are working with objects, lists, or complex types.
Practical Examples and Use Cases
Using const for App Configuration
object Config {
const val BASE_URL = "https://api.softaai.com"
const val DEFAULT_TIMEOUT = 5000
}Here, BASE_URL and DEFAULT_TIMEOUT are known constants that never change.
Using val for Mutable Objects
fun getUsers(): List<String> {
val users = listOf("Amol", "Baban", "Chetan")
return users
}users is immutable, but it holds a list that’s assigned at runtime.
Using val in Jetpack Compose
@Composable
fun Greeting(name: String) {
val greetingMessage = "Hello, $name!" // Evaluated at runtime
Text(text = greetingMessage)
}greetingMessage is assigned dynamically based on the name parameter.
Conclusion
Understanding the difference between const and val is crucial for writing efficient and well-structured Kotlin code. While both ensure immutability, const is for compile-time constants, whereas val is for runtime immutable variables.
By applying the right choice in different scenarios, you can optimize your Kotlin applications for better readability, performance, and maintainability.
