Kotlin特性学习笔记

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{
    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
mList.plus(1)
mList+1
interface MyList{
    fun get(index:Int):T
    operator 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)

你可能感兴趣的:(kotlin,学习,笔记)