val, var and Immutability by Default

val, var and Immutability by Default in Kotlin: --- At the north end of a working dock, each berth carries two pieces of signage and they are made of…


The Analogy: The Bolted Signboard and the Chalkboard at Berth 4

At the north end of a working dock, each berth carries two pieces of signage and they are made of deliberately different materials. Bolted to the quay wall, on four galvanised coach bolts, is an enamel board reading BERTH 4 -- GRAIN. Putting it up took two men and a socket set, and taking it down would take the same. Beside it hangs a slate, and chalked on the slate is the name of whichever vessel is alongside: AURORA this morning, BELLONA on the evening tide, wiped with a damp rag in between. Nobody confuses the two boards. One states what this berth is; the other states what is happening at it right now.

The bolted board is a val. Once it is up, the name it carries cannot be swapped for another name -- not by the crane driver, not by the shift foreman, not by anyone without a spanner and a work order. The slate is a var. Rewriting it is a normal part of the day, and the whole point of hanging a slate rather than bolting a second enamel board is that its contents are expected to change. Kotlin makes you choose which material you are working in at the moment you declare the name, and the choice is visible on the line forever afterwards.

Here is the part that catches people, and it catches them in code exactly as it catches them on the dock. Behind the bolted board stands a silo. The board says GRAIN and the board cannot be changed, and yet the silo is loaded and drawn down all day long: forty tonnes in on the morning conveyor, twelve out to a lorry at noon, another consignment in before dark. Nothing about the bolts on the board restrains the grain. The board fixes which silo you are talking about; it says nothing whatsoever about how much is in it. val cargo = mutableListOf("grain") is precisely this arrangement: the name cargo is bolted to one list forever, and that list will accept as many additions as anyone cares to make.

The failure mode is a stock reconciliation done from the signage. A clerk who has internalised that the enamel board cannot change starts treating everything behind it as equally fixed, writes the tonnage down once at the start of the week, and reconciles Friday's figures against Monday's note. The numbers do not match, and because the board is still bolted on and still perfectly legible, the clerk's first instinct is that the weighbridge is faulty. In Kotlin this is the developer who passes a val list into three functions, assumes it arrives unchanged because the declaration said val, and spends an afternoon on a bug that is one add call in the second function. Fixing the binding is not the same as fixing the contents, and the language provides separate tools for each.


Syntax or Core Structure

val and var differ in one respect only: whether a later assignment to that name is legal. Everything else -- inference, nullability, visibility, what the value can do -- is identical.

const val BERTH_COUNT = 4              // compile-time constant, inlined at call sites

fun main() {
    val berth = "BERTH 4"              // bolted: no reassignment permitted
    var ship = "Aurora"                // chalk: reassigned on the evening tide

    println("$berth holds $ship")
    ship = "Bellona"
    println("$berth holds $ship")

    val cargo = mutableListOf("grain")
    cargo.add("barley")                // legal: the binding is fixed, the list is not
    println("cargo now ${cargo.size}: ${cargo.joinToString(", ")}")

    println("berths on this quay: $BERTH_COUNT")
}

Output:

BERTH 4 holds Aurora
BERTH 4 holds Bellona
cargo now 2: grain, barley
berths on this quay: 4

The third block is the whole lesson in two lines. cargo is declared val, so cargo = mutableListOf() on a later line would not compile -- and cargo.add("barley") compiles happily, because adding does not reassign the name. If you want the contents fixed too, that is a different declaration: val cargo = listOf("grain") has no add method to call.


Technical Depth: What Immutability Actually Buys

Five ways to name a value

Declaration formCan the name be reassignedWhen the value is settled
val n = 1noat initialisation, once
var n = 1yesnever, any later assignment may change it
const val N = 1noat compile time, and copied into every caller
lateinit var s: Stringyes, and must be set before the first readwhenever the code assigns it
val n get() = compute()there is no stored value to reassignnever, the getter runs on every read

The last row is the one that trips people who have learned the rule as "val means constant". A val with a custom getter stores nothing; it is a function wearing a property's clothes, and it may return a different answer every time you touch it. This is why the compiler refuses to smart-cast such a property, and it is worth knowing before you write one.

Read-only is a smaller promise than immutable

Kotlin's collection interfaces separate the ability to read from the ability to write, but the read-only interface is a view, not a guarantee about the data.

What you holdCan you write through itCan the data change underneath you
List<String> obtained from a MutableListnoyes, the owner still has the mutable reference
MutableList<String>yesyes
the result of toList()nono, it is a copy taken at that moment
the result of asReversed()noyes, it is a live view of the same storage
the result of listOf(...)nono, nothing else holds a writable reference

The distinction has a name worth using in review comments: toList() is a snapshot and everything else in that table is a window. If a caller is going to hold on to what you hand back for longer than one function call, hand back a snapshot.


A stored val versus a computed val

class Berth(val name: String, var occupant: String?) {
    // computed on every read: no backing field exists
    val label: String
        get() = if (occupant == null) "$name EMPTY" else "$name $occupant"

    // stored once, at construction: a real backing field
    val bolted: String = "$name FIXED"
}

fun main() {
    val berth = Berth("BERTH 4", null)
    println(berth.label)
    println(berth.bolted)

    berth.occupant = "Aurora"
    println(berth.label)
    println(berth.bolted)
}

Output:

BERTH 4 EMPTY
BERTH 4 FIXED
BERTH 4 Aurora
BERTH 4 FIXED

Both properties are declared val and both are read four times, yet one answer changed and the other did not. bolted was computed once during construction and stored; label is recomputed at each access from a var that moved underneath it. Neither behaviour is wrong, but they are different enough that guessing is expensive: if a property's value depends on mutable state, put a getter on it deliberately, and if it does not, store it and let the compiler enforce that nothing recomputes.

lateinit, and the failure it converts

Sometimes a non-null property genuinely cannot be given a value at construction -- a framework injects it, or a lifecycle callback supplies it. lateinit var says so explicitly, in exchange for a specific exception rather than a null.

class Manifest {
    lateinit var berth: String

    fun assign(name: String) {
        berth = name
    }

    fun describe(): String =
        if (this::berth.isInitialized) "assigned to $berth" else "not yet assigned"
}

fun main() {
    val m = Manifest()
    println(m.describe())
    m.assign("BERTH 4")
    println(m.describe())

    val untouched = Manifest()
    val outcome = try {
        untouched.berth.length
        "read succeeded"
    } catch (e: UninitializedPropertyAccessException) {
        "read failed: ${e::class.simpleName}"
    }
    println(outcome)
}

Output:

not yet assigned
assigned to BERTH 4
read failed: UninitializedPropertyAccessException

lateinit is a trade, not a free pass. What you gain is a property typed String rather than String?, so the rest of the class never writes a null check. What you pay is that the guarantee moves from the compiler to your own discipline, and a premature read throws UninitializedPropertyAccessException instead of being caught at build time. isInitialized exists so that code which genuinely cannot know can ask, and it is only usable from inside the declaring class, which is a hint about how narrowly the feature is meant to be used. It also cannot be applied to Int, Boolean or any other primitive-backed type, because there is no reference slot to leave empty.


Real World Example: The Berth Register at Shift Change

The dock keeps a register of which vessels are alongside. The harbour office needs to read it, the shift foreman needs to write to it, and the two must not be the same privilege. This is the ordinary shape of the problem, and it is where the difference between a window and a snapshot stops being academic.

class BerthRegister {
    private val ships = mutableListOf<String>()

    val roster: List<String>
        get() = ships              // a live window onto the storage

    val snapshot: List<String>
        get() = ships.toList()     // a copy, frozen at the moment of the call

    fun arrive(name: String) {
        ships.add(name)
    }

    fun depart(name: String): Boolean = ships.remove(name)
}

fun main() {
    val register = BerthRegister()
    register.arrive("Aurora")
    register.arrive("Bellona")

    val liveView = register.roster
    val frozen = register.snapshot
    println("live=${liveView.size} frozen=${frozen.size}")

    register.arrive("Corvus")
    println("after arrival: live=${liveView.size} frozen=${frozen.size}")

    val removed = register.depart("Bellona")
    println("departed Bellona: $removed")
    println("after departure: live=${liveView.size} frozen=${frozen.size}")

    println("live contents: ${liveView.joinToString(", ")}")
    println("frozen contents: ${frozen.joinToString(", ")}")

    val missing = register.depart("Draco")
    println("departed Draco: $missing")
    println("final live=${register.roster.size}")
}

Output:

live=2 frozen=2
after arrival: live=3 frozen=2
departed Bellona: true
after departure: live=2 frozen=2
live contents: Aurora, Corvus
frozen contents: Aurora, Bellona
departed Draco: false
final live=2

Follow the two numbers down the page. They start equal at 2, because at the moment both were taken the register held Aurora and Bellona. Corvus arrives and live becomes 3 while frozen stays 2 -- liveView is the same list object the register writes to, and frozen is a copy that stopped existing as a shared thing the instant toList() returned. Bellona departs and live drops back to 2, which is the trap in its purest form: live and frozen are both 2 again, and they now describe entirely different sets of ships. The two contents lines prove it -- Aurora and Corvus against Aurora and Bellona.

Nothing in the declarations warned about that. liveView and frozen are both val, both typed List<String>, both obtained from a property on the same object, one line apart. The only difference is that one getter returned the field and the other returned ships.toList(). A reader of main cannot see which is which; a reader of BerthRegister can. That asymmetry is why the choice belongs in the class rather than at the call site, and why it deserves a comment on the property.

The depart calls illustrate the other half. remove returns true when it removed something and false when the name was not present, so the Draco line reports false without any exception being thrown. That boolean is the only signal a caller gets, and the example does check it -- but only by printing it, which is not the same as handling it.

The limits are worth stating flatly, because this class would pass most code reviews and should not. The design flaw is roster: it returns the private MutableList widened to List, which hides the write methods from the type checker without removing them from the object. Any caller can write (register.roster as MutableList<String>).clear() and empty the register from outside, and the compiler will allow it with only an unchecked-cast warning. Encapsulation implemented by up-casting is a convention, not a boundary. Beyond that: arrive accepts duplicates, so two vessels with the same name make depart remove an arbitrary one of them and report success; there is no capacity limit, so the register will accept a hundred ships at a four-berth quay; and the class is not safe for concurrent use, which matters the moment the harbour office reads while the foreman writes. Returning snapshot from roster fixes the first problem at the cost of a copy per call, and Collections.unmodifiableList fixes it at the cost of a runtime exception instead of a compile error -- neither is free, and choosing between them is the actual design work.


Common Mistakes

  1. Believing that val makes the object immutable. val cargo = mutableListOf("grain") forbids cargo = something and permits cargo.add("barley") on the very next line. The val protects the reference, not the referent. When you need the contents fixed too, the type has to say so: listOf(...), or a data class whose own properties are all val, or a defensive copy at the boundary.
  1. Treating List as a promise of immutability. List<String> means "I will not offer you add", not "nobody can add". If the value underneath is a MutableList that someone else still holds, it can change between two reads of the same val. Kotlin calls these interfaces read-only rather than immutable precisely to keep that distinction visible, and the standard library has no truly immutable list type at all.
  1. Returning the backing collection widened to a read-only type. The roster property above is the canonical version of this: an up-cast is not a copy and not a barrier. If the caller must not mutate, return ships.toList(), or hand back a Sequence, or expose only the operations you intend (size, contains, forEach) instead of the collection itself.
  1. Using var because a value is assigned in more than one branch. var label: String; if (x) label = "a" else label = "b" is almost always better as val label = if (x) "a" else "b", because if and when are expressions in Kotlin. Reaching for var here costs you the guarantee that the name never changes again, and it costs the compiler the ability to prove the value was definitely assigned.
  1. Reading a lateinit var on a path that does not assign it. The compiler stops checking initialisation the moment you write lateinit; you have swapped a compile error for an UninitializedPropertyAccessException at the first read. Use it only where a framework genuinely assigns the field after construction, and guard uncertain reads with this::field.isInitialized rather than a null check, since the property is not nullable.
  1. Expecting const val to work anywhere val does. const val is compile-time only: top level, inside an object, or inside a companion object, and restricted to String and the primitive types. It cannot hold listOf(1, 2), cannot live inside a normal class body, and cannot have a custom getter. A plain val in a companion object is the fallback, and it is initialised at class load rather than inlined at each use site.
  1. Writing a val with a getter and then treating it as a stored value. val label get() = ... runs its body on every single read. If that body sorts a list or formats a string, a loop that reads the property a thousand times does the work a thousand times. Stored vals compute once at construction. Choose deliberately, and if the computation is expensive and the inputs never change, use by lazy instead.
  1. Assuming that two reads of the same val property must agree. They must for a stored val of an immutable type. They need not for a computed val, because its getter can read var state, and they need not for a val holding a mutable object. The label property in the depth section returns two different strings across two reads without ever being reassigned.
  1. Making a property var and public in the same breath. A public var gives every caller in the program permission to write, forever, and you cannot take it back without breaking source compatibility. private set costs one line and keeps the read side identical: var occupant: String? = null; private set. Widening later is easy; narrowing later is a breaking change.

Best Practices

  • Start every declaration as val and change it to var only when the compiler forces you. The IDE will tell you immediately, and the resulting count of vars in a file becomes a fair measure of how much mutable state it really needs.
  • Say which kind of collection you mean in the type, not in a comment. val ships: MutableList<String> and val ships: List<String> document two different contracts, and the second one makes accidental writes a compile error rather than a code-review finding.
  • Copy at the boundary. When a constructor takes a collection you did not create, store items.toList(); when a getter hands one out, return items.toList() unless a live view is the documented intent. One allocation buys you the guarantee that nobody outside can reach in.
  • Comment computed vals that are not obviously cheap, and prefer by lazy when the result is expensive and stable. A reader cannot tell val a: Int = compute() from val a: Int get() = compute() at the call site, so the declaration is the only place the difference can be recorded.
  • Put program-wide constants in const val at the top level of a file or in an object, and give them screaming snake case. They are inlined into call sites, cost nothing at runtime, and appear in the bytecode as literals -- which also means changing one requires recompiling every module that read it.
  • Prefer private set over a public var whenever writes belong to the class. It keeps the property syntax at the read site, avoids a hand-written getter, and moves every mutation into methods you can name, log and test.
  • Treat lateinit as a framework accommodation rather than a convenience. If you are writing the code that constructs the object, pass the value to the constructor; if a dependency injector or a lifecycle callback assigns it, lateinit is the honest description of that arrangement.
  • Make immutability structural where it matters: data class with all-val properties plus copy() gives you cheap "changed" versions without any writable state, and it is what lets equality, hashing and set membership stay correct over time.

Practice Exercises

  1. Write a class Quay with a private MutableList<String> of berthed ships and three public read paths: live (returns the backing list as List<String>), frozen (returns toList()), and count (returns size). In main, take one of each, add a ship, and print all three; then cast live back to MutableList<String>, call clear() on it, and print count. Explain in a comment which of the three read paths survived the attack and why.
  1. Take class Berth(val name: String, var occupant: String?) and add two properties: a stored val stamped: String and a computed val current: String, both built from name and occupant. Construct one Berth, print both properties, change occupant, print both again, and state in a comment how many times each property's expression was evaluated across the whole run.
  1. Declare a const val MAX_BERTHS = 4 at the top level, then try to declare const val BERTH_NAMES = listOf("A", "B") next to it and record the compiler's exact complaint in a comment. Replace it with whatever declaration does work, and explain in one sentence why the list version cannot be a const val.
  1. Write a class Manifest with a lateinit var berth: String. Add a function describe(): String that returns "berth unknown" when the property has not been assigned and "berth $berth" when it has, using this::berth.isInitialized rather than a null check. Call describe() before and after assigning, then delete the guard and record which exception the unguarded read throws.