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
- Operator Functions
- Comparison Operators
- Index and Invoke
- Best Practices