为什么Kotlin在运算符重载之外使用运算符修饰符?
我对Kotlin中operator
修饰符的用法有点困惑。 例如,Kotlin在解构声明和属性委托中使用了operator
修饰符,恕我直言(原谅我的无知),有点混乱,因为这两种情况都是在运算符重载之外的。
解构:
operator fun <K, V> Map<K, V>.iterator(): Iterator<Map.Entry<K, V>> = entrySet().iterator() operator fun <K, V> Map.Entry<K, V>.component1() = getKey() operator fun <K, V> Map.Entry<K, V>.component2() = getValue() for ((key, value) in map) { // ... }
属性委托:
interface ReadOnlyProperty<in R, out T> { operator fun getValue(thisRef: R, property: KProperty<*>): T } interface ReadWriteProperty<in R, T> { operator fun getValue(thisRef: R, property: KProperty<*>): T operator fun setValue(thisRef: R, property: KProperty<*>, value: T) }
我假定Kotlin operator
意思是“通过名称约定访问”,对于运算符( plus()
, minusAssign()
等),组件访问器( component1()
等),对于循环访问iterator
( iterator
, hasNext
)和委托访问器( getValue
等)