Kotlin

val vs var — Prefer Immutability

admin by @admin ADMIN
3d ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`val` is read-only (can't reassign the reference); `var` is mutable. Default to `val` everywhere — Kotlin's style guide recommends it, and a Compiler warning fires if a `var` is never reassigned.
Kotlin
Raw
fun main() {
    val name = "Alice"          // read-only — can't reassign
    // name = "Bob"             // compile error

    var counter = 0             // mutable — needed because we increment it
    counter += 1
    counter += 1
    println("$name $counter")   // Alice 2

    // val refers to the SAME object — the object itself can still be mutable
    val list = mutableListOf(1, 2, 3)
    list.add(4)                 // OK — we're mutating the list, not reassigning `list`
    println(list)               // [1, 2, 3, 4]

    // Top-level / member: backing field semantics
    class Counter {
        var n = 0                // mutable property
        val label = "hits"       // immutable property
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.