1. 基本对应关系
val lambda0: () -> String = { \"hello\" } val lambda1: (Int) -> String = { it.toString() } val lambda2: (Int, String) -> Boolean = { i, s -> i > 0 }
2. 编译器生成的实现类
val lambda: (Int) -> String = { it.toString() }class Lambda$1 : Function1<Int, String> { override fun invoke(p1: Int): String { return p1.toString() }}
3. 挂起 Lambda
的特殊情况
val normalLambda: (Int) -> String = { it.toString() }/ 挂起 Lambda val suspendLambda: suspend (Int) -> String = { it.toString() }
4. Function
接口的层次结构
interface Function<out R>interface Function0<out R> : Function<R> { operator fun invoke(): R}interface Function1<in P1, out R> : Function<R> { operator fun invoke(p1: P1): R}interface Function2<in P1, in P2, out R> : Function<R> { operator fun invoke(p1: P1, p2: P2): R}
5. 挂起函数的 Function
接口
interface SuspendFunction0<out R> : Function<R>interface SuspendFunction1<in P1, out R> : Function<R>
6. 实际编译示例
val add: (Int, Int) -> Int = { a, b -> a + b }val add = object : Function2<Int, Int, Int> { override fun invoke(p1: Int, p2: Int): Int { return p1 + p2 }}
7. 挂起 Lambda
的完整编译
val suspendAdd: suspend (Int, Int) -> Int = { a, b -> delay(100) a + b }class SuspendLambda$1 : SuspendLambda(2), Function3<Int, Int, Continuation<Int>, Any?> { override fun invoke(p1: Int, p2: Int, continuation: Continuation<Int>): Any? { return create(p1, p2, continuation).invokeSuspend(Result.success(Unit)) } override fun invokeSuspend(result: Result<Any?>): Any? { when (label) { 0 -> { label = 1 return delay(100, this) } 1 -> { return arg1 + arg2 } } }}
8. 核心规律总结
Lambda 类型 |
编译后实现 |
特点 |
() -> R |
Function0 |
无参数 |
(P1) -> R |
Function1 |
单参数 |
(P1, P2) -> R |
Function2 |
双参数 |
suspend () -> R |
SuspendLambda + Function1 |
挂起无参 |
suspend (P1) -> R |
SuspendLambda + Function2 |
挂起单参 |
10. 关键差异
- 普通
Lambda
:
- 直接实现对应的
FunctionN
接口
invoke
方法直接执行逻辑
- 挂起
Lambda
:
- 继承
SuspendLambda
(也是 BaseContinuationImpl
)
- 实现
FunctionN+1
接口(额外的 Continuation
参数)
- 包含状态机逻辑处理挂起点