fun main(arg: Array<String>) {
val myClass1 = myClass1()
myClass1.name="mycalsss1" val myClass2 = myClass2()
myClass2.name="myclass2"
println(myClass1.name)
println(myClass2.name)
}
class myClass1{
var name:String =""
get() :String{
println("mycalsss1.get 被调用")
return field
}
set(value:String) {
println("myclass1.set 被调用")
field=value
}
}
class myClass2{
var name:String =""
get() :String{
println("mycalsss2.get 被调用")
return field
}
set(value:String) {
println("myclass2.set 被调用")
field=value
}
}

输出:

myclass1.set 被调用
myclass2.set 被调用
mycalsss1.get 被调用
mycalsss1
mycalsss2.get 被调用
myclass2

上面代码冗余,所谓委托类,就是一个包含getValue和setValue函数的类,这两个函数operator声明

在使用委托类时,需要by关键字,创建委托类实例的代码放在by后面

如下

import kotlin.reflect.KProperty

fun main(arg: Array<String>) {
val myClass1 = myClass1()
myClass1.name = "mycalss1" val myClass2 = myClass2()
myClass2.name = "myclass2"
println(myClass1.name)
println(myClass2.name)
} class delegate {
var name: String = ""
operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
val classname = thisRef.toString().substringBefore("@")
println("$classname get被调用")
return name
} operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
val classname = thisRef.toString().substringBefore("@")
println("$classname set被调用")
name = value
}
} class myClass1 {
var name: String by delegate() } class myClass2 { var name: String by delegate()
}

输出结果和上面一样!

05-24 07:21