1,关键字by修饰类,表示类委托 interface Animation{fun eat() }//动态代理 class Dog:Animation{override fun eat() {println("dog eat oligarch")} }class DogProxy:Animation by Dog(){}
2,关键字by修饰变量,实现属性委托
var name:String by NameDelegate()class NameDelegate:ReadWriteProperty<Any?,String>{override fun getValue(thisRef: Any?, property: KProperty<*>): String {println(property.name)return property.name}override fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {println(value)} }
3,operator修饰方法,表示重写操作符
lateinit var mList:MyList<Int> mList.plus(1) mList+1 interface MyList<out T>{fun get(index:Int):Toperator fun plus(t: @UnsafeVariance T)operator fun div(t: @UnsafeVariance T)operator fun minus(t: @UnsafeVariance T) }
kotlin所有运算操作符:
一元操作符(Unary Operators) | ||
+a | a.unaryPlus() | |
-a | a.unaryMinus() | |
!a | a.not() | |
a++ | a.inc() | |
二元操作符( Binary Operators) | ||