> 技术文档 > Kotlin -> Kotlin Lambda 表达式与 Function 接口的关系

Kotlin -> Kotlin Lambda 表达式与 Function 接口的关系


1. 基本对应关系

// Lambda 表达式 -> 编译后的 Function 接口val lambda0: () -> String = { \"hello\" }  // Function0val lambda1: (Int) -> String = { it.toString() }  // Function1 val lambda2: (Int, String) -> Boolean = { i, s -> i > 0 } // Function2// ... 最多到 Function22

2. 编译器生成的实现类

val lambda: (Int) -> String = { it.toString() }// 编译器生成类似这样的代码:class Lambda$1 : Function1<Int, String> { override fun invoke(p1: Int): String { return p1.toString() }}

3. 挂起 Lambda 的特殊情况

// 普通 Lambdaval normalLambda: (Int) -> String = { it.toString() }// 实现: Function1// 挂起 Lambda val suspendLambda: suspend (Int) -> String = { it.toString() }// 实现: SuspendFunction1 + Function2<Int, Continuation, Any?>

4. Function 接口的层次结构

// Kotlin 标准库中的定义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>// 但实际编译后实现的是:// SuspendFunction1 -> Function2<P1, Continuation, Any?>

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 参数)
    • 包含状态机逻辑处理挂起点