kotlin 委托类的初始化函数

import java.beans.AppletInitializer
import kotlin.reflect.KProperty

fun main(arg: Array<String>) {
    val myClass1 = myClass1()
    myClass1.name = "mycalss1 name"

    val myClass2 = myClass2()
    myClass2.name = "myclass2 name"
    println(myClass1.name)
    println(myClass2.name)
}

class delegate<T>(initializer: ()-> T) {
    var name: String = ""
    var classname =initializer()
    operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
        println("$classname get被调用")
        return name
    }

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
        println("$classname set被调用")
        name = value
    }
}

class myClass1 {
    var name: String by delegate(){
        println(" myClass1 初始化函数被调用")
    }

}

class myClass2 {

    var name: String by delegate(){
        println(" myClass2 初始化函数被调用")

    }
}

输出:

 myClass1 初始化函数被调用
kotlin.Unit set被调用
 myClass2 初始化函数被调用
kotlin.Unit set被调用
kotlin.Unit get被调用
mycalss1 name
kotlin.Unit get被调用
myclass2 name

 

posted on 2018-12-19 14:31  LoaderMan  阅读(800)  评论(0编辑  收藏  举报

导航