kotlin 里面的如何处理多个lambda函数参数?

在 Kotlin 中,可以通过以下方式实现函数接收多个 Lambda 表达式 作为参数,其中 Kotlin 中每个 Lambda 参数在底层会被编译为一个 ​**FunctionN 接口的匿名类实例**​(N 表示参数个数)。

其本质是

  1. 编译为函数对象 :每个 Lambda 转换为 FunctionN 接口的实例。
  2. 内存与性能权衡:非内联 Lambda 有对象分配开销,内联 Lambda 通过代码展开消除开销。
  3. 语法糖优化:尾随 Lambda 和命名参数提升多 Lambda 调用的可读性。

1. ​基础示例:直接声明多个 Lambda 参数

kotlin 复制代码
fun runMultipleLambdas(
    action1: () -> Unit,
    action2: (String) -> Int,
    action3: (Int) -> Boolean
) {
    action1()
    val result = action2("test")
    action3(result)
}

// 调用方式(显式命名参数,推荐):
runMultipleLambdas(
    action1 = { println("Action1!") },
    action2 = { s -> s.length },
    action3 = { num -> num > 0 }
)

2. ​利用 Trailing Lambda 语法

如果某个 Lambda 是最后一个参数,可以将其放在括号外:

kotlin 复制代码
fun withTrailingLambda(
    before: () -> Unit,
    after: (String) -> Unit
) {
    before()
    after("Done")
}

// 调用方式:
withTrailingLambda(
    { println("Starting...") }  // before 参数
) { s ->                       // after 参数(Trailing Lambda)
    println("Result: $s")
}

3. ​为 Lambda 参数提供默认值

让某些 Lambda 成为可选参数:

kotlin 复制代码
fun flexibleLambdas(
    mandatory: (Int) -> Unit,
    optional: (String) -> Unit = { _ -> } // 默认空实现
) {
    mandatory(42)
    optional("optional")
}

// 调用方式:
flexibleLambdas({ println(it) }) // 只传必要的 Lambda
flexibleLambdas(
    mandatory = { println("Mandatory: $it") },
    optional = { println("Optional: $it") }
)

4. ​使用高阶函数处理多个 Lambda

结合 invoke 调用或其他逻辑:

kotlin 复制代码
fun processData(
    data: List<Int>,
    onEven: (Int) -> Unit,
    onOdd: (Int) -> Unit
) {
    data.forEach {
        if (it % 2 == 0) onEven(it) else onOdd(it)
    }
}

// 调用方式:
processData(listOf(1, 2, 3),
    onEven = { println("Even: $it") },
    onOdd = { println("Odd: $it") }
)

5. ​通过类型别名提升可读性

为复杂的 Lambda 类型定义别名:

kotlin 复制代码
typealias Parser<T> = (String) -> T?
typealias Logger = (String) -> Unit

// 由于parseInput返回的Int,因此parser参数对应的是 Parser<Int>,
// 如果函数返回值是泛型,则可以灵活写成 parser: Parser<T>
fun parseInput(
    input: String,
    parser: Parser<Int>,
    log: Logger = { println(it) }
): Int? {
    log("Parsing: $input")
    return parser(input)
}

// 调用方式:
val result = parseInput("123", { it.toIntOrNull() })

关键注意事项:

  • 参数顺序:调用时需按顺序传递,或使用命名参数明确指定。
  • 可读性:多个 Lambda 建议换行并命名参数,避免歧义。
  • 性能 :Lambda 在 JVM 上会生成匿名类,频繁调用可考虑内联(inline 关键字)。

通过上述方法,可以灵活地在 Kotlin 函数中传递和处理多个 Lambda 表达式。

相关推荐
whysqwhw41 分钟前
安卓上WebRtc
android
青莲8431 小时前
内联函数 inline noinline crossinline reified
android
wayne2141 小时前
从 MVC 到 MVI:Android 架构演进全景剖析与示例代码
android
我又来搬代码了3 小时前
【Android】【bug】Json解析错误Expected BEGIN_OBJECT but was STRING...
android·json·bug
CANI_PLUS12 小时前
ESP32将DHT11温湿度传感器采集的数据上传到XAMPP的MySQL数据库
android·数据库·mysql
来来走走13 小时前
Flutter SharedPreferences存储数据基本使用
android·flutter
安卓开发者15 小时前
Android模块化架构深度解析:从设计到实践
android·架构
雨白15 小时前
HTTP协议详解(二):深入理解Header与Body
android·http
阿豪元代码15 小时前
深入理解 SurfaceFlinger —— 如何调试 SurfaceFlinger
android
阿豪元代码15 小时前
深入理解 SurfaceFlinger —— 概述
android