Kotlin – 覆盖/实现类似数组的访问器函数
是否有可能覆盖或实现Kotlin中的[]
访问器(使用操作符重载或类似)?
val testObject = MyCustumObject() println(testObject["hi"]) // ie implement this accessor.
在Python中,这可以通过实现__getitem__
和__setitem__
来实现。
在Kotlin中,需要实现的是get
和set
运算符函数 :
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]") } }
用法:
val c = C() val a = c["123", 4] // "1234" c[1, 2] = "abc" // Putting abc at [1, 2]
你可以使用任意数量的参数定义get
和set
(当然至少有一个)。 另外, set
具有在作为其最后一个parameter passing的使用站点上分配的expression式:
-
a[i_1, ..., i_n]
被翻译成a.get(i_1, ..., i_n)
-
a[i_1, ..., i_n] = b
被转换为a.set(i_1, ..., i_n, b)
get
和set
也可以有不同的重载,例如:
class MyOrderedMap { // ... operator fun get(index: Int): Pair = ... // i-th added mapping operator fun get(key: K): V = ... // value by key }
注意:这个例子为MyOrderedMap
引入了不希望的歧义MyOrderedMap
因为两个get
函数都会匹配像m[1]
这样的调用。
正如文件中所述, a[i]
被翻译为a.get(i)
。 例如:
class MyObject { operator fun get(ix:Int):String{ return "hello $ix" } }
让你写:
val a = MyObject() println(a[123]) //-> "hello 123"
类似地, a[i] = b
被转换为一个方法调用a.set(i, b)
。
你必须重写get()。
https://kotlinlang.org/docs/reference/operator-overloading.html
a[i] translates to a.get(i)