classDelegate{ operatorfungetValue(thisRef: Any?, property: KProperty<*>): String { return"$thisRef, thank you for delegating '${property.name}' to me!" } operatorfunsetValue(thisRef: Any?, property: KProperty<*>, value: String) { println("$value has been assigned to '${property.name}' in $thisRef.") } }
classExample{ var p: String by Delegate() } funmain(){ val e = Example() println(e.p) //Example@33a17727, thank you for delegating ‘p’ to me! e.p = "NEW"//NEW has been assigned to ‘p’ in Example@33a17727. }
属性委托要求:
对于val: 委托必须提供一个操作符函数 getValue(),该函数具有以下参数:
thisRef —–必须与属性所有者类型(对于扩展属性–指被扩展的类型)相同或者是其超类
property—— 必须是类型KProperty<*>` 或其超类型。
1 2 3 4 5 6 7 8 9
classResource classOwner{ val valResource: Resource by ResourceDelegate() } classResourceDelegate{ operatorfungetValue(thisRef: Owner, property: KProperty<*>): Resource { return Resource() } }