2016-11-21 75 views

回答

4

在科特林,它是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] 

您可以定义getset与参数任意数量指数(至少一个,当然);此外,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)

getset也可以有不同的过载,例如:

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]电话。

4

the documentationa[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)