概念和实现原理
Receiver是函数接受者的意思,它的实现原理其实就是在函数的参数列表中添加一个Receiver的实例 如下
fun String.f1(){
this.toString()
}
反编译后
public final void f1(String $this$f1) {
$this$f1.toString();
}
Recevier的作用
Receivier的根本作用是给函数传递一个Receiver对象,那么函数内部就能够调用这个Receiver对象的相关方法
Receiver的应用场景
一. 扩展函数
站在类的角度上看,就是给类扩展函数。
这个对于面向对象编程的开发者来说其实很好。
因为面向对象编程,接触的是一个个类,然后给类扩展方法,正是我们日常所需要的
fun String.toFloat(): Float {
return java.lang.Float.parseFloat(this)
}
fun test(){
"jack".toFloat()
}
二.给函数扩展功能
这需要站在函数的角度看待问题了,我们有一个函数,我们想让它具有其他类的功能。 以<<kotlin协程>>第四章,仿phthon的Generator来说。 block函数的作用是产生序列,但是我们需要它具有让函数挂起的功能,所以给它添加了一个GeneratorScope的Receiver,那在block内部就可以使用yeild()方法挂起
class GeneratorIterator<T>(
private val block: suspend GeneratorScope<T>.(T) -> Unit,
private val parameter: T
) : GeneratorScope<T>, Iterator<T>, Continuation<Any?> {
override val context: CoroutineContext = EmptyCoroutineContext
private var state: State
init {
val coroutineBlock: suspend GeneratorScope<T>.() -> Unit =
{ block(parameter) }
val start = coroutineBlock.createCoroutine(this, this)
state = State.NotReady(start)
}
}
val nums = generator { start: Int ->
for (i in 0..5) {
yield(start + i)
}
}