0Pricing
Kotlin Academy · Lesson

Index and Invoke

get, set, and invoke.

The Index Operator

Defining operator fun get lets you read with bracket syntax: obj[i].

class Row(val cells: List<String>) {
    operator fun get(i: Int) = cells[i]
}

fun main() {
    val r = Row(listOf("a", "b", "c"))
    println(r[1])
}

Writing with set

operator fun set enables assignment: obj[i] = value. The last parameter is the value.

class Grid {
    private val data = IntArray(3)
    operator fun get(i: Int) = data[i]
    operator fun set(i: Int, value: Int) { data[i] = value }
}

fun main() {
    val g = Grid()
    g[0] = 42
    println(g[0])
}

All lessons in this course

  1. Operator Functions
  2. Comparison Operators
  3. Index and Invoke
  4. Best Practices
← Back to Kotlin Academy