是否可以在Kotlin中覆盖或实现[]
访问器(使用操作符重载或类似操作)?Kotlin - 覆盖/实现类似数组的访问器函数
val testObject = MyCustumObject()
println(testObject["hi"]) // i.e. implement this accessor.
在Python这是可能的通过实施__getitem__
和__setitem__
。
是否可以在Kotlin中覆盖或实现[]
访问器(使用操作符重载或类似操作)?Kotlin - 覆盖/实现类似数组的访问器函数
val testObject = MyCustumObject()
println(testObject["hi"]) // i.e. implement this accessor.
在Python这是可能的通过实施__getitem__
和__setitem__
。
在科特林,它是get
and set
operator functions,你需要实现:
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
有其是在利用网站作为其最后一个参数传递赋予表达式:
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<K, V> {
// ...
operator fun get(index: Int): Pair<K, V> = ... // i-th added mapping
operator fun get(key: K): V = ... // value by key
}
注:本例介绍不良歧义的MyOrderedMap<Int, SomeType>
因为两个get
功能会匹配m[1]
电话。
您必须重写get()。
https://kotlinlang.org/docs/reference/operator-overloading.html
a[i] translates to a.get(i)
如the documentation的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)
。