CodeGym /課程 /Kotlin SELF /Indexer get/set: obj[i], obj[i, j]

Indexer get/set: obj[i], obj[i, j]

Kotlin SELF
等級 38, 課堂 3
開放

1. Introduction

When you see code like list[0] or map["mode"], your brain spends almost no effort reading it: 「we took an element by index/key」. That is the power of indexers: they make data access short and familiar. But there is a downside: the shorter the notation, the easier it is to hide surprising rules inside.

That is why indexers are useful in two cases: when the action really looks like access to a cell/element, and when you are ready to describe error behaviour honestly. Otherwise, a regular method is better: getById(...), which immediately hints: 「there may be logic here」.

How Kotlin understands obj[i] and obj[i] = value

From the compiler’s point of view, an expression in square brackets is not a 「special operation」; it is simply a convenient way to write function calls named get and set. And here it is important to get used to the idea: you do not 「turn on an indexer」; you write regular functions, but mark them with operator, so the compiler allows the [] syntax.

Kotlin states it straightforwardly: a[i] becomes a.get(i), and the assignment a[i] = b — into a.set(i, b); for multiple indices the principle is the same.

Below is a mini 「translation」 table worth keeping in mind (this is literally a compiler rule, not someone’s opinion):

Code notation What it compiles to
a[i]
a.get(i)
a[i, j]
a.get(i, j)
a[i] = b
a.set(i, b)
a[i, j] = b
a.set(i, j, b)

The same principle works for any number of indices: a[i1, i2, i3] → a.get(i1, i2, i3).

2. Indexers in the standard library: List and Map

Before writing your own get/set, it helps to notice: we have been using them for a long time; we just did not call them 「operator functions」.

List: has get, but no set

When you have List<T>, you can read an element by index, but you cannot modify the list via [] =, because List is a read-only interface.

fun main() {
    val names: List<String> = listOf("Ann", "Bob")
    println(names[0]) // Ann
    // names[0] = "Kate" // compilation error: List has no set
}

MutableList: set appears, so [] = works

fun main() {
    val names: MutableList<String> = mutableListOf("Ann", "Bob")
    names[1] = "Kate"
    println(names) // [Ann, Kate]
}

Your brain reads this as 「replaced the element by index」, and that is a good contract: no hidden logic, a pure replacement.

Map: key-based indexer and null as part of the contract

With Map it is more interesting, because reading by key typically returns V?, that is null, if the key is missing. This is not an 「inconvenience」; it is the official contract.

fun main() {
    val ages: Map<String, Int> = mapOf("Ann" to 20)
    println(ages["Ann"])   // 20
    println(ages["Bob"])   // null
}

And with MutableMap writing works too:

fun main() {
    val settings = mutableMapOf<String, String>()
    settings["mode"] = "debug"
    println(settings["mode"]) // debug
}

Notice: here set almost always means 「put/replace the value by key」. That is predictable — and predictability is exactly what we will try to preserve when we build our own indexers.

3. Our own indexers in the educational app BudgetBuddy

Now let’s integrate indexers into our practical console app. Let it be called BudgetBuddy and store a list of expenses. Previously we most likely made functions like addExpense(...), listExpenses(), findById(...). Today we will add 「convenient access」 on top of the existing data model.

We will do three small steps: introduce a type ExpenseId, a model Expense, and a container ExpenseBook that supports book[index] and book[id].

ExpenseId as a separate type

If both index and id are Int, it is easy to mix up the meaning accidentally. To make the code self-documenting, we use a value class (already familiar from previous topics): it is a 「wrapper over a number」, but with its own type.

@JvmInline
value class ExpenseId(val value: Int)

Now ExpenseId(10) and just 10 are different entities, and the compiler will not let you accidentally 「pass an index instead of an id」. It is like a conference badge: same face, but the label helps avoid mixing people up.

Expense model

For simplicity, let the amount be stored in cents (this avoids Double issues). If you already have Money from earlier examples — great, but to avoid bloating the code, we will keep Long here.

data class Expense(
    val id: ExpenseId,
    val title: String,
    val amountCents: Long
)

ExpenseBook container and position-based indexer

Let’s start with the most familiar: index access like a list. Inside ExpenseBook there will be a MutableList<Expense>. The indexer get(index) must do bounds checking; otherwise you will crash somewhere deep inside, and the message will be less friendly.

class ExpenseBook {
    private val items = mutableListOf<Expense>()

    fun add(expense: Expense) {
        items.add(expense)
    }

    operator fun get(index: Int): Expense {
        require(index in items.indices) { "No expense with index $index" }
        return items[index]
    }
}

Now you can do this:

fun main() {
    val book = ExpenseBook()
    book.add(Expense(ExpenseId(1), "Coffee", 250))

    println(book[0]) // Expense(id=ExpenseId(value=1), title=Coffee, amountCents=250)
}

The key point: book[0] reads as 「the first expense」, and that is true.

set(index, value): replacement by index

If we want book[0] = ..., we need operator fun set(index, value).

class ExpenseBook {
    private val items = mutableListOf<Expense>()

    fun add(expense: Expense) { items.add(expense) }

    operator fun set(index: Int, value: Expense) {
        require(index in items.indices) { "Cannot write at index $index" }
        items[index] = value
    }
}

Usage:

fun main() {
    val book = ExpenseBook()
    book.add(Expense(ExpenseId(1), "Coffee", 250))

    book[0] = Expense(ExpenseId(1), "Coffee (large)", 350)
    println(book[0].title) // Coffee (large)
}

And here it is important not to overcomplicate it: [] = is almost always expected as replacement. If you make it so that book[0] = x 「adds a new element to the end」 or 「sums values」, the class user will be completely confused. Yes, formally you can, but it will be like a hot-water tap that sometimes pours coffee: unexpected and mentally unsafe.

4. Contracts, bounds, and indexer design

The most practical part of indexers is not operator, but the decision: how your type behaves on error. In the Kotlin world there are several common styles, and it is important to choose one and be consistent.

Fail-fast or nullable

Fail-fast means: if the index is invalid, throw an exception via require(...). This is a good approach when an invalid index is a programmer error, and it is better to fail immediately with a clear message.

The nullable approach means: if the element is missing, return null. This is a good approach when the absence of an element is normal (as with Map[key]).

In a table it looks like this:

Approach get signature What happens when missing
Fail-fast
operator fun get(index: Int): Expense
exception (IllegalArgumentException via require)
Nullable
operator fun get(id: ExpenseId): Expense?
returns null

Often it makes sense to have both variants, but for different 「index types」. For list indices you usually expect fail-fast, because the index is almost always computed by code. For id it is often more convenient to return null, because 「such an id does not exist」 can be a search result.

Indexer by ExpenseId: book[id]

Let’s add lookup by id to ExpenseBook. Here we will use a nullable contract (like Map).

class ExpenseBook {
    private val items = mutableListOf<Expense>()

    fun add(expense: Expense) { items.add(expense) }

    operator fun get(id: ExpenseId): Expense? =
        items.firstOrNull { it.id == id }
}

Usage:

fun main() {
    val book = ExpenseBook()
    book.add(Expense(ExpenseId(1), "Coffee", 250))

    println(book[ExpenseId(1)]?.title) // Coffee
    println(book[ExpenseId(2)]?.title) // null
}

Pay attention to ?.title: since get returns Expense?, we must handle null safely. This is not the compiler being pedantic — it is protection against 「I was sure the element exists, but it doesn’t」.

set by id: be careful with expectations

It is very tempting to do book[id] = expense and internally 「if it exists — replace, if not — add」. Such an upsert can be handy, but it has an unpleasant side effect: assignment stops being obvious. The reader does not know: are we updating an existing one or creating a new one?

In educational code, I recommend a stricter but honest contract: set(id, value) updates only an existing element and fails if there is no such id. Creating a new element is left for add(...).

class ExpenseBook {
    private val items = mutableListOf<Expense>()

    fun add(expense: Expense) { items.add(expense) }

    operator fun set(id: ExpenseId, value: Expense) {
        require(value.id == id) { "value.id must match the key id" }

        val index = items.indexOfFirst { it.id == id }
        require(index >= 0) { "No expense with id=${id.value}" }

        items[index] = value
    }
}

Usage:

fun main() {
    val book = ExpenseBook()
    book.add(Expense(ExpenseId(1), "Coffee", 250))

    book[ExpenseId(1)] = Expense(ExpenseId(1), "Coffee (large)", 350)
    println(book[ExpenseId(1)]?.amountCents) // 350
}

Yes, a bit more code. But assignment now has a normal meaning: 「update an existing record」. And it trains contract discipline very well.

How to design an indexer so it doesn’t become a riddle

An indexer is a tool for expressiveness, but it easily turns into 「a trick for the sake of a trick」. It helps to fix a few practical principles.

A good indexer almost always behaves like container access: reading should not change state; writing should be a write, not a 「complex operation disguised as assignment」. Bounds checking should be explicit via require(...) with a decent message, or the contract should explicitly promise null/a default. If you do a third thing (for example, 「on an invalid index return the last element」), it may be convenient exactly once — and then a group of people with flashlights will investigate it.

It helps to mentally substitute the compiler’s translation: if your code looks like obj[i], the reader thinks 「get」; if obj[i] = v, they think 「set」. And semantically set is assignment into a cell, not 「add, merge, recalculate a report, and email accounting」.

5. Multiple indices: obj[i, j]

When people first see obj[i, j], many experience a micro-shock: 「is this a 2D array?」 Sometimes yes, sometimes no. In Kotlin, square brackets with two indices are just a call to get(i, j) or set(i, j, value).

The clearest example is a table, grid, or matrix. In BudgetBuddy, you can imagine we have an 「expense plan」: categories × months, and we want to access it as plan[category, month].

Categories as an enum

enum class Category {
    FOOD, TRANSPORT, FUN
}

BudgetPlan: limits by the pair (category, month)

To keep the example short, let the month be just an index 1..12 (no dates). Inside, we store a LongArray for each category.

class BudgetPlan {
    private val limits = mutableMapOf<Category, LongArray>()

    operator fun get(category: Category, month: Int): Long {
        require(month in 1..12) { "Month must be 1..12" }
        val arr = limits[category] ?: LongArray(12)
        return arr[month - 1]
    }
}

Usage:

fun main() {
    val plan = BudgetPlan()
    println(plan[Category.FOOD, 1]) // 0
}

Now reading always returns 0 for an 「empty」 plan — that is a valid contract if you consider a missing limit equivalent to zero. But it is important to state: this is a business decision, not syntax.

set(category, month, value)

class BudgetPlan {
    private val limits = mutableMapOf<Category, LongArray>()

    operator fun set(category: Category, month: Int, value: Long) {
        require(month in 1..12) { "Month must be 1..12" }
        require(value >= 0) { "Limit cannot be negative" }

        val arr = limits.getOrPut(category) { LongArray(12) }
        arr[month - 1] = value
    }
}

Usage:

fun main() {
    val plan = BudgetPlan()
    plan[Category.FOOD, 1] = 30_000
    println(plan[Category.FOOD, 1]) // 30000
}

Why index order is part of the contract

It is easy to make the 「forever UI bug」 here: swap month and category. The compiler will help because the types are different (and that is good), but in a more general case indices can have the same type, e.g. Int, Int as (x, y) — and then confusion becomes a real threat.

So the rule is simple: choose a parameter order once (for example, (category, month) or (x, y)) and stick to it everywhere. If your type is logically a 「table of rows and columns」, it is often convenient to fix 「first the key-column, then the coordinate-number」 or the other way around — but the main thing is consistency across the whole project.

6. Typical mistakes when working with indexers

Mistake 1: you forgot the operator modifier on get or set.
This mistake looks like 「why doesn’t obj[i] compile, I wrote fun get(i: Int)」. The answer is simple: for square brackets, the compiler looks specifically for an operator function. Without operator this is a regular method, which you can only call as obj.get(i).

Mistake 2: get and set have different bounds contracts.
Sometimes get carefully checks the index via require(...), while set directly accesses the array and crashes with IndexOutOfBoundsException. As a result you get 「either the library broke or I did」. Contracts should be symmetrical: if you cannot read by index, you cannot write either, and the error message should be equally understandable.

Mistake 3: set performs an unexpected operation instead of writing.
It is tempting to do book[id] = expense and internally 「if it didn’t exist — add it」. Then someone writes book[id] = book[id]!! trying to “change nothing”, and you unexpectedly change element order or create a duplicate. Bracket assignment should mean writing into a cell, otherwise reading code turns into guesswork.

Mistake 4: index order is not fixed, and both variants appear in the project.
One day you write grid[x, y], another day — grid[row, col], and a week later you do grid[y, x], because 「that’s how it is in matrices」. This is not a joke; it is a classic bug that later looks like 「everything calculates, but the answers are weird」. Index order is part of the API and must be standardized from the start.

Mistake 5: missing consistency checks in set.
If you implement set(id, value) to update a record, it is useful to verify that value.id == id. Without this you can accidentally store 「an expense with id=7」 under the key ExpenseId(3) and silently corrupt data. Such checks feel pedantic right up until you catch a bug like 「why does the March report show expenses from August」.

Mistake 6: the indexer is used for heavy computations and side effects.
Because obj[i] looks like a lightweight operation, the reader expects it to be O(1) or close, and definitely without surprises. If inside get you sort, recalculate a report, or log, you will get very strange slowdowns and even stranger call sites. For heavy actions, use an honest method name: recalculateTotals() is longer, but it does not lie.

1
任務
Kotlin SELF, 等級 38, 課堂 3
上鎖
橫幅字元
橫幅字元
1
任務
Kotlin SELF, 等級 38, 課堂 3
上鎖
比賽計分板
比賽計分板
1
任務
Kotlin SELF, 等級 38, 課堂 3
上鎖
模式設定
模式設定
1
任務
Kotlin SELF, 等級 38, 課堂 3
上鎖
實驗室格網
實驗室格網
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION