Val vs Var in Kotlin: Key Differences and Usage Guide
val declares a read-only variable that cannot be reassigned after initialization, while var declares a mutable variable that can be changed. Use val when you want a constant reference and var when you need to update the value.Quick Comparison
Here is a quick side-by-side comparison of val and var in Kotlin.
| Factor | val | var |
|---|---|---|
| Mutability | Immutable (cannot reassign) | Mutable (can reassign) |
| Initialization | Must be initialized once | Must be initialized once |
| Reassignment | Not allowed | Allowed |
| Use case | For constants or fixed references | For variables that change |
| Thread safety | Safer by default | Less safe if shared |
| Performance | Potentially optimized by compiler | Standard variable |
Key Differences
val creates a read-only reference. Once you assign a value to a val variable, you cannot change it later. This makes your code safer because you know the value won't accidentally change. It is similar to a constant but can hold objects whose internal state might still change.
var creates a mutable reference. You can assign a new value to a var variable anytime after initialization. This flexibility is useful when the data needs to change, like counters or user input values.
Choosing between val and var affects code readability and safety. Using val by default encourages immutability, which reduces bugs and makes your program easier to understand.
Code Comparison
Here is an example using val to declare a variable that cannot be reassigned.
fun main() {
val name = "Alice"
println(name)
// name = "Bob" // This will cause a compile error
}var Equivalent
Here is the same example using var, allowing reassignment.
fun main() {
var name = "Alice"
println(name)
name = "Bob"
println(name)
}When to Use Which
Choose val whenever possible to make your code safer and easier to maintain by preventing accidental changes. Use var only when you need to update the variable's value over time, such as counters, flags, or user inputs. Starting with val and switching to var only when necessary is a good practice.
Key Takeaways
val for variables that should not change after assignment.var for variables that need to be reassigned.val promotes safer, more predictable code.val and switch to var only if needed.var offers flexibility but requires careful use to avoid bugs.