Skip to workspace
Kotlin Lab

Everyday Kotlin / Chapter 01

Choose val or var

Track a warehouse balance without losing intermediate stock levels.

The decision

The warehouse records stock after each adjustment. Stock can reach zero. A later delivery must still be counted in full. Which names need to change during the calculation?

Read the Kotlin

Follow the value into the next iteration

Read the function signature from left to right. fun declares a function, a parameter’s type follows its name, and the type after the closing parenthesis is the result. Inside the loop, var lets each assignment replace the previous stock. Start at 3 and apply −8, then +2. The first assignment stores zero, so the next addition starts at zero. History gets one entry per change.

var stock = 3
stock = (stock - 8).coerceAtLeast(0)  // 0
stock = (stock + 2).coerceAtLeast(0)  // 2

Read the type to find the available operations

When you leave off a local type, the compiler infers it from the expression on the right. listOf<Int>() gives you a List<Int> with operations such as size and contains. Its interface has no add. The factory mutableListOf<Int>() gives you a MutableList<Int>, whose interface also declares add. You can see the same difference through two names for one object.

val writer = mutableListOf(6)
val reader: List<Int> = writer
writer.add(7)          // reader now sees [6, 7]
// reader.add(8)       // would fail to compile

Choose the binding and the collection separately

Ask two questions when declaring an accumulator. Will this name point at another list? Will the current list gain entries? A Java final ArrayList can grow, and the same combination in Kotlin is a val holding a mutable list. Changing the declaration to var would allow reassignment. It would give a read-only list no additional methods.

val totals = mutableListOf<Int>()
totals.add(12)                    // updates this list
// totals = mutableListOf(15)     // would reassign the name

The full example

Java 25
import java.util.ArrayList;
import java.util.List;

class Lesson {
    static List<Integer> levels(int initial, List<Integer> changes) {
        int stock = initial;
        final var history = new ArrayList<Integer>();
        for (var change : changes) {
            stock = Math.max(0, stock + change);
            history.add(stock);
        }
        return List.copyOf(history);
    }
}
Kotlin/JVM
fun levels(initial: Int, changes: List<Int>): List<Int> {
    var stock = initial
    val history = mutableListOf<Int>()
    for (change in changes) {
        stock = (stock + change).coerceAtLeast(0)
        history.add(stock)
    }
    return history
}

Inputs and outcomes

InputOutcomeWhy it matters
Start at 4, adjustments −3 and +2[1, 3]Record a balance after each adjustment.
Start at 2, adjustments −5 and +3[0, 3]Clamp immediately. Carrying a negative balance would leave zero after the delivery.
Start at 6, no adjustments[]The opening balance is outside the history.

Walk through the code

  1. Each iteration reads the preceding stock and then replaces it, so stock uses var. The changes parameter already acts as a read-only binding.
  2. history uses val because each add writes into the same list. Java’s final var combines a fixed reference with local type inference. In Kotlin, both val and var can infer a type.
  3. The public return type exposes read operations. The function never shares its private accumulator while constructing the history. Java returns an unmodifiable copy. Kotlin’s List type alone promises a read-only interface.

The Java habit

Declaring every collection var to make add available confuses assignment with mutation. The receiver needs a mutable collection type to support add.

When to choose differently

If several components share a mutable history, val does little to protect it. Take an independent snapshot at the ownership boundary when later mutations must be invisible.

References

Open quizTry code