CodeGym /Courses /Kotlin SELF /Indexing operators get/set: obj[i], obj[i, j]

Indexing operators get/set: obj[i], obj[i, j]

Kotlin SELF
Level 38, Lesson 3
Available

1. Introduction

When you see code like list[0] or map["mode"], your brain barely spends any energy reading it: “we took an element by index/key.” That’s the power of indexers—they make data access short and familiar. But there’s also a downside: the shorter the notation, the easier it is to hide unexpected rules inside.

That’s why indexers are useful in two cases: when the action really does look like accessing a cell/element, and when you’re ready to honestly describe the behavior on errors. Otherwise, a regular method like getById(...), is better, because it 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,” but simply a convenient notation for calling functions named get and set. And it’s important to get used to this idea: you don’t “enable an indexer,” you write ordinary functions but mark them operator, so the compiler allows the [] syntax.

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

Below is a mini “translation” table you should keep 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’s useful to notice: we’ve been using them for a long time—we just didn’t call them “operator functions.”

List: has get, but no set

When you have List<T>, you can read an element by index, but you can’t 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" // compile 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 “we replaced an element by index,” and that’s a good contract: no hidden logic, a pure replacement.

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

With Map it’s more interesting, because reading by key typically returns V?, i.e. null, if the key is missing. This isn’t an “unpleasantness”—it’s 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
}

Note: here set almost always means “put/replace the value by key.” That’s predictable—and predictability is exactly what we’ll try to preserve when we make our own indexers.

3. Custom indexers in the training app BudgetBuddy

Now let’s integrate indexers into our practical console app. Let’s say it’s called BudgetBuddy and stores a list of expenses. Previously, we most likely had functions like addExpense(...), listExpenses(), findById(...). Today we’ll add “convenient access” on top of an existing data model.

We’ll take three small steps: introduce an ExpenseId type, an Expense model, and an ExpenseBook container that will support book[index] and book[id].

ExpenseId as a separate type

If both an index and an id are Int, it’s easy to accidentally mix up their meaning. To make the code self-documenting, we’ll use a value class (already familiar from previous topics): it’s a “wrapper around 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 won’t let you accidentally “pass an index instead of an id.” It’s like a badge at a conference: the face is the same, but the label helps you not confuse people.

Expense model

For simplicity, let the amount be stored in cents (this avoids Double problems). If you already have a Money type from previous examples—great, but to keep the code from ballooning, we’ll use 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 thing: index access like a list. Inside ExpenseBook we’ll have a MutableList<Expense>. The get(index) indexer must do bounds checking; otherwise you’ll get a 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)
}

Key point: book[0] reads as “the first expense,” and that’s 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 this is where it’s important not to “overthink” it: [] = is almost always expected to mean 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 it’s possible, but it’ll be like a hot-water tap that sometimes pours coffee: unexpected and psychologically 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’s 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’s better to fail immediately with a clear message.

The nullable approach means: if the element doesn’t exist, return null. This is a good approach when absence is a normal situation (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 a list index, fail-fast is usually expected, because the index is almost always computed by code. For an id, returning null is often more convenient, because “that id doesn’t exist” can be the result of a search.

Indexer by ExpenseId: book[id]

Let’s add lookup by id to ExpenseBook. Here we’ll 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. And this isn’t the compiler being pedantic—it’s protection from the situation “I was sure the element exists, but it doesn’t.”

set by id: be careful with expectations

It’s very tempting to make book[id] = expense and implement “if it exists—replace it, if not—add it” inside. Such an upsert is sometimes convenient, but it has an unpleasant side effect: assignment stops being obvious. The reader can’t tell: are we updating an existing entry or creating a new one?

In training code, I recommend a stricter but honest contract: set(id, value) updates only an existing element and fails if that id doesn’t exist. And we leave creation of a new element to 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 id key" }

        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 gets a clear meaning: “update an existing record.” And it trains contract discipline really well.

How to design an indexer so it doesn’t turn into 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 lock in a few practical principles.

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

It’s useful to mentally substitute the compiler’s desugaring: if your code looks like obj[i], the reader thinks “get”; if it’s obj[i] = v, they think “set.” And set, semantically, is assignment into a cell—not “add, merge, recalculate a report, and email the accountant.”

5. Multiple indices: obj[i, j]

When people first see obj[i, j], many have 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, a grid, or a matrix. In BudgetBuddy, you can imagine that we have a “spending plan”: categories × months, and we want to access it like plan[category, month].

Categories as an enum

enum class Category {
    FOOD, TRANSPORT, FUN
}

BudgetPlan: limits by (category, month) pair

To keep the example short, let the month be just an index 1..12 (no dates). Internally, 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
}

Right now, reading always yields 0 for an “empty” plan—that’s a normal contract if you consider the absence of a limit equivalent to zero. But it’s 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 the index order is part of the contract

It’s easy to make the “eternal UI dev mistake” here: swap month and category. The compiler won’t help because the types are different (and that’s good), but in a more general case the indices may have the same type—for example, Int, Int as (x, y)—and then confusion becomes a real threat.

So the rule is very simple: choose the 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’s usually convenient to fix “first the column key, then the row index,” or the other way around—but the main thing is to be consistent across the whole project.

6. Common mistakes when working with indexers

Mistake #1: you forgot the operator modifier on get or set.
This looks like: “why doesn’t obj[i] compile? I wrote fun get(i: Int).” The answer is simple: for square brackets, the compiler looks for an operator function specifically. Without operator, it’s just a regular method that can only be called as obj.get(i).

Mistake #2: get and set have different bounds contracts.
Sometimes get carefully checks the index via require(...), but set directly pokes into the array and crashes with IndexOutOfBoundsException. As a result you get “either the library is broken or I am.” Contracts should be symmetric: if you can’t read by index, you can’t write either, and the error message should be equally clear.

Mistake #3: set performs an unexpected operation instead of writing.
It’s very tempting to do book[id] = expense and implement “if it wasn’t there—add it.” Then someone writes book[id] = book[id]!! trying to “change nothing,” and you suddenly reorder elements or create a duplicate. Bracket assignment should mean writing into a cell; otherwise reading code turns into guesswork.

Mistake #4: the index order isn’t 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 isn’t a joke; it’s a classic bug that later looks like “everything computes, but the answers are weird.” Index order is part of the API, and it needs to be standardized right away.

Mistake #5: no data-consistency checks in set.
If you implement set(id, value) to update an entry, it’s useful to check that value.id == id. Without this, you can accidentally write “an expense with id=7” under the key ExpenseId(3) and silently corrupt the data. These checks feel pedantic right up until you catch the bug “why does the March report show expenses from August?”

Mistake #6: using an indexer for heavy computations and side effects.
Since obj[i] looks like a lightweight operation, the reader expects it to be O(1) or close to it—and definitely without surprises. If inside get you do sorting, recompute a report, or log something, you’ll get very strange slowdowns and even stranger call sites. For heavy actions, a method with an honest name is better: recalculateTotals() is longer, but it doesn’t lie.

1
Task
Kotlin SELF, level 38, lesson 3
Locked
Banner character
Banner character
1
Task
Kotlin SELF, level 38, lesson 3
Locked
Tournament scoreboard
Tournament scoreboard
1
Task
Kotlin SELF, level 38, lesson 3
Locked
Mode settings
Mode settings
1
Task
Kotlin SELF, level 38, lesson 3
Locked
Lab grid
Lab grid
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION