In Kotlin, it is [`get` and `set` operator functions](
[To see links please register here]
) that you need to implement:
class C {
operator fun get(s: String, x: Int) = s + x
operator fun set(x: Int, y: Int, value: String) {
println("Putting $value at [$x, $y]")
}
}
And the usage:
val c = C()
val a = c["123", 4] // "1234"
c[1, 2] = "abc" // Putting abc at [1, 2]
You can define `get` and `set` with arbitrary number of parameters for *indices* (at least one, of course); in addition, `set` has the expression which is assigned at the use site passed as its last argument:
* `a[i_1, ..., i_n]` is translated to `a.get(i_1, ..., i_n)`
* `a[i_1, ..., i_n] = b` is translated to `a.set(i_1, ..., i_n, b)`
`get` and `set` can have different overloads as well, for example:
class MyOrderedMap<K, V> {
// ...
operator fun get(index: Int): Pair<K, V> = ... // i-th added mapping
operator fun get(key: K): V = ... // value by key
}
<sup>Note: this example introduces undesirable ambiguity for `MyOrderedMap<Int, SomeType>` since both `get` functions will match calls like `m[1]`.</sup>