Val vs Var in Kotlin: Key Differences and Usage Guide
val declares a read-only variable whose value cannot be changed after initialization, while var declares a mutable variable that can be reassigned. Use val for constants or values that should not change, and var when you need to update the variable later.Quick Comparison
Here is a quick side-by-side comparison of val and var in Kotlin.
| Aspect | val | var |
|---|---|---|
| Mutability | Immutable (read-only reference) | Mutable (can be reassigned) |
| Reassignment allowed? | No | Yes |
| Initialization requirement | Must be initialized once | Must be initialized once |
| Use case | Constants, fixed values | Variables that change |
| Thread safety | Safer for concurrency | Less safe if shared |
| Performance | Potentially optimized by compiler | Standard variable |
Key Differences
The main difference between val and var lies in mutability. A val variable is like a locked box: once you put a value inside, you cannot change it. This makes your code safer and easier to understand because you know the value won't change unexpectedly.
On the other hand, var is like a reusable container that you can open and replace the contents anytime. This flexibility is useful when the value needs to change during program execution, such as counters or user input.
Both val and var must be initialized before use, but only var allows reassignment after initialization. Choosing between them affects code readability, safety, and sometimes performance.
Val Example
fun main() {
val name = "Alice"
println(name)
// name = "Bob" // Error: Val cannot be reassigned
}Var Equivalent
fun main() {
var age = 25
println(age)
age = 26
println(age)
}When to Use Which
Choose val when you want to create a variable that should not change after it is set. This helps prevent bugs and makes your code easier to follow. Use var only when you need to update the variable's value later, such as in loops, counters, or when tracking state changes.
As a best practice, prefer val by default and switch to var only when necessary. This approach leads to safer and more predictable code.
Key Takeaways
val for variables that should not change after initialization.var for variables that need to be reassigned or updated.val improves code safety and readability by preventing accidental changes.val and var before use.val by default and use var only when mutability is required.