val vs var
In this page:
Declaring with val
val creates a reference that can be assigned a value exactly once. Attempting to assign a new value to a val after that is a compile-time error, which helps prevent accidental changes.
Note: Prefer val everywhere possible; it makes code easier to reason about.
Example: Declaring with val
fun main() {
val name = "Kotlin"
println("Language: $name")
}
Login to try C/C++/Java/PHP code in the editor
Declaring with var
var creates a mutable reference whose value can be changed later using =. It is used when a value genuinely needs to change over the program's lifetime, such as a running counter.
Example: Declaring with var
fun main() {
var counter = 0
counter = counter + 1
counter += 1
println("Counter is now $counter")
}
Login to try C/C++/Java/PHP code in the editor
val Reference vs Mutable Contents
A val only locks the reference itself, not necessarily what it points to. A val holding a mutable list still lets you add or remove items -- you just cannot point that val at a different list afterward.
Note: If you need the contents to be unchangeable too, use an immutable collection type.
Example: val Reference vs Mutable Contents
fun main() {
val items = mutableListOf("apple", "banana")
items.add("cherry")
println(items)
}
Login to try C/C++/Java/PHP code in the editor
Choosing val Over var
Idiomatic Kotlin favors val by default and reaches for var only when a variable must be reassigned. This habit reduces bugs caused by unexpected mutation and makes code easier to follow.
Example: Choosing val Over var
fun main() {
val pi = 3.14159
var radius = 2.0
radius = 3.0
println("Area: ${pi * radius * radius}")
}
Login to try C/C++/Java/PHP code in the editor
- Trying to reassign a
valand being surprised by a compiler error;valmeans read-only, not just a stylistic default. - Overusing
varout of habit from other languages, when most values in Kotlin never actually need to change. - Thinking
valmakes an object itself immutable; it only prevents reassigning the variable, the object's own contents can still change.
valdeclares a read-only reference; it can be assigned once and never reassigned.vardeclares a mutable reference that can be reassigned as many times as needed.- Preferring
valby default is idiomatic Kotlin; usevaronly when reassignment is truly needed. valdoes not make the referenced object immutable -- aval listcan still have items added to it.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: