val vs var
Kotlin has two keywords for declaring a variable. val (value) is read-only: it is assigned once and can never point at something else. var (variable) can be reassigned. Idiomatic Kotlin uses val everywhere it can and reaches for var only when a value genuinely changes — a counter, a running total. Fewer things that change means fewer places a bug can hide.
fun main() {
val name = "Asha" // read-only
var score = 10 // reassignable
score = score + 5
score += 5
println("$name scored $score")
}Asha scored 20Add score -= 3 before the println and predict the new output.
val cannot be reassigned
fun main() {
val count = 1
count = 2
println(count)
}Main.kt:3:5: error: 'val' cannot be reassigned.count is a val, so the compiler guarantees it keeps its first value. Assigning again breaks that promise and the file does not compile.
If the value really must change, declare it with var. If it should not, create a new val with a different name instead.
fun main() {
var count = 1
count = 2
println(count)
}val list = mutableListOf(1, 2) cannot be pointed at a different list, but list.add(3) still works — the reference is fixed, the object it points to can change. Module 05 covers read-only versus mutable collections.