Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - Override/Implement array-like accessor function

Tags:

kotlin

Is it possible to override or implement the [] accessors in Kotlin (using operator overloading or similar)?

val testObject = MyCustumObject()
println(testObject["hi"])  // i.e. implement this accessor.

In Python this is possible by implementing __getitem__ and __setitem__.

like image 404
Robin Nabel Avatar asked Nov 21 '16 13:11

Robin Nabel


1 Answers

In Kotlin, it is get and set operator functions 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
}

Note: this example introduces undesirable ambiguity for MyOrderedMap<Int, SomeType> since both get functions will match calls like m[1].

like image 121
hotkey Avatar answered Oct 22 '22 11:10

hotkey