1.委托是什么?

1.1 官网示例

  在每个变量委托的实现的背后,Kotlin 编译器都会生成辅助对象并委托给它。 假设委托如下,

 class C {
var prop: Type by MyDelegate()
}

  那么编译器生成的相应代码如下:

 class C {
private val prop$delegate = MyDelegate()
var prop: Type
get() = prop$delegate.getValue(this, this::prop)
set(value: Type) = prop$delegate.setValue(this, this::prop, value)
}

  其中:

  • val prop$delegate 就是被委托的对象
  • getValue与setValue就是对prop的管理函数

1.2 变量委托是一系列类

  变量委托是重载setValue,getValue运算符的类,可直接重载或者实现ReadWriteProperty、ReadOnlyProperty 接口之一。

     operator fun getValue(thisRef: R, property: KProperty<*>): T
operator fun setValue(thisRef: R, property: KProperty<*>, value: T)

  其中

  • thisRef —— 必须与委托都类型相同或者是它的超类型;
  • property —— 必须是类型 KProperty<*> 或其超类型。
  • value 必须与委托者同类型或者是它的子类型
  • 返回值与委托者相同类型(或其子类型)

  下面看下lazy是怎么实现的

 val i11 by lazy {  }

  点开lazy的实现

/**
* Creates a new instance of the [Lazy] that uses the specified initialization function [initializer]
* and the default thread-safety mode [LazyThreadSafetyMode.SYNCHRONIZED].
*
* If the initialization of a value throws an exception, it will attempt to reinitialize the value at next access.
*
* Note that the returned instance uses itself to synchronize on. Do not synchronize from external code on
* the returned instance as it may cause accidental deadlock. Also this behavior can be changed in the future.
*/
public actual fun <T> lazy(initializer: () -> T): Lazy<T> = SynchronizedLazyImpl(initializer)

  lazy是个函数 ,返回Lazy<T> ,再看下Lazy

 /**
* Represents a value with lazy initialization.
*
* To create an instance of [Lazy] use the [lazy] function.
*/
public interface Lazy<out T> {
/**
* Gets the lazily initialized value of the current Lazy instance.
* Once the value was initialized it must not change during the rest of lifetime of this Lazy instance.
*/
public val value: T /**
* Returns `true` if a value for this Lazy instance has been already initialized, and `false` otherwise.
* Once this function has returned `true` it stays `true` for the rest of lifetime of this Lazy instance.
*/
public fun isInitialized(): Boolean
}

  并没有operator getValue,往下看

 /**
* An extension to delegate a read-only property of type [T] to an instance of [Lazy].
*
* This extension allows to use instances of Lazy for property delegation:
* `val property: String by lazy { initializer }`
*/
@kotlin.internal.InlineOnly
public inline operator fun <T> Lazy<T>.getValue(thisRef: Any?, property: KProperty<*>): T = value

  原来它是扩展重载的getValue运算符。

  再看下Delegates.observable,它返回的 ObservableProperty 实现了 ReadWriteProperty 接口。

    /**
* Returns a property delegate for a read/write property that calls a specified callback function when changed.
* @param initialValue the initial value of the property.
* @param onChange the callback which is called after the change of the property is made. The value of the property
* has already been changed when this callback is invoked.
*
* @sample samples.properties.Delegates.observableDelegate
*/
public inline fun <T> observable(initialValue: T, crossinline onChange: (property: KProperty<*>, oldValue: T, newValue: T) -> Unit):
ReadWriteProperty<Any?, T> =
object : ObservableProperty<T>(initialValue) {
override fun afterChange(property: KProperty<*>, oldValue: T, newValue: T) = onChange(property, oldValue, newValue)
}
 public abstract class ObservableProperty<T>(initialValue: T) : ReadWriteProperty<Any?, T> {

     //...
public override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return value
} public override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
val oldValue = this.value
if (!beforeChange(property, oldValue, value)) {
return
}
this.value = value
afterChange(property, oldValue, value)
}
}

2.by后面的是什么?

  by后面的是委托类的一个对象

  示例代码

 class lazy11(var default : Int = -,var lmda : () -> Int) {
operator fun provideDelegate( thisRef : Any,prop : KProperty<*>) : Delegate13 {
return Delegate13(lmda)
}
} val i11 by lazy { } class D11{
val MAX by lazy { } var lazy = lazy{ }
val value : Int by lazy var lazy11 = lazy11{}
var count : Int by lazy11
} fun delegate_test11(){
Log.e(TAG_DELEGATE,"====================================== delegate_test_11 ") var d11 = D11()
Log.e(TAG_DELEGATE,"d11.value = ${d11.value},d11.count = ${d11.count} ,d11.MAX = ${d11.MAX}")
}

  结果

2019-09-13 16:54:51.742 10374-10374/com.example.kotlin E/delegate: ====================================== delegate_test_11
2019-09-13 16:54:51.744 10374-10374/com.example.kotlin E/delegate: Delegate13.getValue
2019-09-13 16:54:51.744 10374-10374/com.example.kotlin E/delegate: d11.value = 9,d11.count = 8 ,d11.MAX = 1024

  其中:MAX委托的是编译器生成的对象,而value与count则是直接托委的成员对象。

3.自定义变量委托

3.1 直接重载getValue,setValue运算符

 class BYY{
var value : Int = - operator fun setValue(thisRef: Any, property: KProperty<*>, v : Int) {
Log.e(TAG_DELEGATE,"BYY.setValue")
value = v
}
operator fun getValue(thisRef: Any, property: KProperty<*>): Int {
Log.e(TAG_DELEGATE,"BYY.getValue")
return value
}
}
operator fun BYY.setValue(thisRef: Nothing?, property: KProperty<*>, v : Int){ }
operator fun BYY.get(thisRef: Nothing?, property: KProperty<*>) = value class D12{
var size : Int by BYY()
} fun delegate_test12(){
Log.e(TAG_DELEGATE,"====================================== delegate_test_12 ")
var d12 = D12()
d12.size =
Log.e(TAG_DELEGATE,"d12.size = ${d12.size}") }

  结果

2019-09-13 17:02:43.564 10695-10695/com.example.kotlin E/delegate: ====================================== delegate_test_12
2019-09-13 17:02:43.564 10695-10695/com.example.kotlin E/delegate: BYY.setValue
2019-09-13 17:02:43.564 10695-10695/com.example.kotlin E/delegate: BYY.getValue
2019-09-13 17:02:43.564 10695-10695/com.example.kotlin E/delegate: d12.size = 128

3.2 实现 委托接口

  ReadOnlyProperty 与 ReadWriteProperty 这两个接口声明了getValue,setValue两个运算符,

 class MyDelegate() : ReadOnlyProperty<DC12,Int>,ReadWriteProperty<DC12,Int>{
var value : Int =
override fun setValue(thisRef: DC12, property: KProperty<*>, v : Int) {
Log.e(TAG_DELEGATE,"MyDelegate.setValue ")
value = v
} override fun getValue(thisRef: DC12, property: KProperty<*>) : Int {
Log.e(TAG_DELEGATE,"MyDelegate.setValue ")
return value
}
constructor(lmda : ()-> Int) : this (){
value = lmda()
}
}
fun getNum() : Int{
Log.e(TAG_DELEGATE,"getNum ")
return
} class DC12{
var value : Int by MyDelegate()
var value2 : Int by MyDelegate(::getNum)
} fun delegate_test12(){
Log.e(TAG_DELEGATE,"====================================== delegate_test_12 ") var dc12 = DC12()
dc12.value =
Log.e(TAG_DELEGATE,"dc12.value = ${dc12.value},dc12.value2 = ${dc12.value2}")
}

  结果

2019-09-13 17:04:07.213 10931-10931/com.example.kotlin E/delegate: ====================================== delegate_test_12
2019-09-13 17:04:07.214 10931-10931/com.example.kotlin E/delegate: getNum
2019-09-13 17:04:07.214 10931-10931/com.example.kotlin E/delegate: MyDelegate.setValue
2019-09-13 17:04:07.214 10931-10931/com.example.kotlin E/delegate: MyDelegate.setValue
2019-09-13 17:04:07.214 10931-10931/com.example.kotlin E/delegate: MyDelegate.setValue
2019-09-13 17:04:07.214 10931-10931/com.example.kotlin E/delegate: dc12.value = 64,dc12.value2 = 33

3.3 委托提供运算符 provideDelegate

  如果 by 右侧所使用的对象将 provideDelegate 定义为成员或扩展函数,那么会调用该函数来创建属性委托实例。

 class Delegate13 (lmda: () -> Int) : ReadOnlyProperty<Any,Int>,ReadWriteProperty<Any,Int>{
var COUNT : Int
init{
COUNT = lmda()
}
override fun setValue(thisRef: Any, property: KProperty<*>, value: Int) {
Log.e(TAG_DELEGATE,"Delegate13.setValue")
COUNT = value
}
override fun getValue(thisRef: Any, property: KProperty<*>): Int {
Log.e(TAG_DELEGATE,"Delegate13.getValue")
return COUNT
}
}
class mutableLazy(var default : Int = -,var lmda : () -> Int) {
operator fun provideDelegate( thisRef : Any,prop : KProperty<*>) : Delegate13 {
return Delegate13(lmda)
}
} class D13{
var value : Int by mutableLazy{
Log.e(TAG_DELEGATE,"mutableLazy.lmda") }
} fun delegate_test13(){
Log.e(TAG_DELEGATE,"====================================== delegate_test_13 ") var d13 = D13()
Log.e(TAG_DELEGATE,"d13.value = ${d13.value}") d13.value =
Log.e(TAG_DELEGATE,"d13.value = ${d13.value}")
}

  结果

2019-09-13 20:52:31.350 25146-25146/com.example.kotlin E/delegate: ====================================== delegate_test_13
2019-09-13 20:52:31.350 25146-25146/com.example.kotlin E/delegate: mutableLazy.lmda
2019-09-13 20:52:31.350 25146-25146/com.example.kotlin E/delegate: Delegate13.getValue
2019-09-13 20:52:31.350 25146-25146/com.example.kotlin E/delegate: d13.value = 99
2019-09-13 20:52:31.350 25146-25146/com.example.kotlin E/delegate: Delegate13.setValue
2019-09-13 20:52:31.350 25146-25146/com.example.kotlin E/delegate: Delegate13.getValue
2019-09-13 20:52:31.351 25146-25146/com.example.kotlin E/delegate: d13.value = 299
05-24 07:21