Kotlin Lambda 表达式 #
一、Lambda 基础 #
1.1 什么是 Lambda #
Lambda 是一种匿名函数,可以作为值传递和使用。
1.2 Lambda 语法 #
kotlin
{ 参数列表 -> 函数体 }
1.3 基本示例 #
kotlin
// 完整语法
val sum = { a: Int, b: Int -> a + b }
// 调用
sum(10, 20) // 30
// 另一种调用方式
sum.invoke(10, 20)
1.4 Lambda 类型 #
kotlin
val sum: (Int, Int) -> Int = { a, b -> a + b }
val greet: (String) -> String = { name -> "Hello, $name" }
val action: () -> Unit = { println("Action") }
二、Lambda 参数 #
2.1 显式参数 #
kotlin
val add = { a: Int, b: Int -> a + b }
val square = { x: Int -> x * x }
2.2 隐式参数 it #
当 Lambda 只有一个参数时,可以使用 it:
kotlin
// 显式参数
val double = { x: Int -> x * 2 }
// 使用 it
val double: (Int) -> Int = { it * 2 }
// 常见用法
listOf(1, 2, 3).map { it * 2 } // [2, 4, 6]
2.3 无参数 Lambda #
kotlin
val sayHello = { println("Hello") }
sayHello()
三、Lambda 与集合 #
3.1 map #
kotlin
val numbers = listOf(1, 2, 3, 4, 5)
val doubled = numbers.map { it * 2 }
// [2, 4, 6, 8, 10]
val strings = numbers.map { "Number: $it" }
// ["Number: 1", "Number: 2", ...]
3.2 filter #
kotlin
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val evens = numbers.filter { it % 2 == 0 }
// [2, 4, 6, 8, 10]
val greaterThanFive = numbers.filter { it > 5 }
// [6, 7, 8, 9, 10]
3.3 reduce #
kotlin
val numbers = listOf(1, 2, 3, 4, 5)
val sum = numbers.reduce { acc, n -> acc + n }
// 15
val product = numbers.reduce { acc, n -> acc * n }
// 120
3.4 fold #
kotlin
val numbers = listOf(1, 2, 3, 4, 5)
val sum = numbers.fold(0) { acc, n -> acc + n }
// 15
val result = numbers.fold(10) { acc, n -> acc + n }
// 25
3.5 其他常用操作 #
kotlin
val list = listOf(1, 2, 3, 4, 5)
// find
list.find { it > 3 } // 4
// any
list.any { it > 3 } // true
// all
list.all { it > 0 } // true
// none
list.none { it < 0 } // true
// count
list.count { it % 2 == 0 } // 2
// partition
val (evens, odds) = list.partition { it % 2 == 0 }
// evens = [2, 4], odds = [1, 3, 5]
// groupBy
val grouped = list.groupBy { if (it % 2 == 0) "even" else "odd" }
// {odd=[1, 3, 5], even=[2, 4]}
四、闭包 #
4.1 捕获变量 #
Lambda 可以捕获外部变量:
kotlin
var counter = 0
val increment = { counter++ }
increment() // counter = 1
increment() // counter = 2
increment() // counter = 3
4.2 修改捕获的变量 #
kotlin
fun createCounter(): () -> Int {
var count = 0
return { count++ }
}
val counter = createCounter()
counter() // 0
counter() // 1
counter() // 2
4.3 实际应用 #
kotlin
fun createLogger(prefix: String): (String) -> Unit {
return { message -> println("$prefix: $message") }
}
val logger = createLogger("APP")
logger("Started") // APP: Started
logger("Processing") // APP: Processing
五、Lambda 与高阶函数 #
5.1 作为参数 #
kotlin
fun operate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
return operation(a, b)
}
operate(10, 5) { x, y -> x + y } // 15
operate(10, 5) { x, y -> x * y } // 50
5.2 尾随 Lambda #
当 Lambda 是最后一个参数时,可以放在括号外:
kotlin
// 普通写法
list.map({ it * 2 })
// 尾随 Lambda
list.map { it * 2 }
// 多参数函数
fun process(value: Int, transform: (Int) -> Int): Int {
return transform(value)
}
process(10) { it * 2 } // 20
5.3 带接收者的 Lambda #
kotlin
fun StringBuilder.buildString(action: StringBuilder.() -> Unit): String {
this.action()
return toString()
}
val result = StringBuilder().buildString {
append("Hello")
append(", ")
append("Kotlin")
}
// "Hello, Kotlin"
六、Lambda 与匿名函数 #
6.1 匿名函数 #
kotlin
// Lambda
val sum1 = { a: Int, b: Int -> a + b }
// 匿名函数
val sum2 = fun(a: Int, b: Int): Int = a + b
// 完整匿名函数
val sum3 = fun(a: Int, b: Int): Int {
return a + b
}
6.2 return 的区别 #
kotlin
// Lambda 中的 return
fun example1() {
listOf(1, 2, 3, 4, 5).forEach {
if (it == 3) return // 返回整个函数
println(it)
}
println("Done") // 不会执行
}
// 匿名函数中的 return
fun example2() {
listOf(1, 2, 3, 4, 5).forEach(fun(it) {
if (it == 3) return // 只返回匿名函数
println(it)
})
println("Done") // 会执行
}
七、函数引用 #
7.1 引用顶层函数 #
kotlin
fun square(x: Int) = x * x
// 使用函数引用
val func = ::square
func(5) // 25
// 传递给高阶函数
listOf(1, 2, 3).map(::square) // [1, 4, 9]
7.2 引用成员函数 #
kotlin
class Person(val name: String) {
fun greet() = "Hello, $name"
}
val person = Person("Kotlin")
// 绑定引用
val greet = person::greet
greet() // "Hello, Kotlin"
// 未绑定引用
val greetFunc = Person::greet
greetFunc(person) // "Hello, Kotlin"
7.3 引用构造函数 #
kotlin
class User(val name: String, val age: Int)
// 引用构造函数
val createUser = ::User
val user = createUser("Kotlin", 10)
八、实战示例 #
8.1 链式操作 #
kotlin
data class Person(val name: String, val age: Int)
val people = listOf(
Person("Alice", 25),
Person("Bob", 30),
Person("Charlie", 20),
Person("David", 35)
)
val result = people
.filter { it.age >= 25 }
.map { it.name }
.sorted()
.joinToString(", ")
// "Alice, Bob, David"
8.2 条件构建 #
kotlin
fun buildList(builder: MutableList<Int>.() -> Unit): List<Int> {
val list = mutableListOf<Int>()
list.builder()
return list
}
val list = buildList {
add(1)
add(2)
add(3)
}
// [1, 2, 3]
8.3 回调处理 #
kotlin
fun fetchData(
onSuccess: (String) -> Unit,
onError: (Exception) -> Unit
) {
try {
val data = "Data from server"
onSuccess(data)
} catch (e: Exception) {
onError(e)
}
}
fetchData(
onSuccess = { println("Success: $it") },
onError = { println("Error: ${it.message}") }
)
8.4 DSL 构建 #
kotlin
class HtmlBuilder {
private val elements = mutableListOf<String>()
fun body(content: () -> Unit) {
elements.add("<body>")
content()
elements.add("</body>")
}
fun p(text: String) {
elements.add("<p>$text</p>")
}
override fun toString() = elements.joinToString("\n")
}
fun html(builder: HtmlBuilder.() -> Unit): String {
return HtmlBuilder().apply(builder).toString()
}
val result = html {
body {
p("Hello, Kotlin!")
p("Lambda is powerful!")
}
}
九、最佳实践 #
9.1 使用 it 简化 #
kotlin
// 单参数时使用 it
list.map { it * 2 }
// 多参数时使用显式名称
list.reduce { acc, element -> acc + element }
9.2 提取复杂 Lambda #
kotlin
// 不推荐
list.filter { it.age > 18 && it.name.startsWith("A") && it.isActive }
// 推荐
fun isEligible(person: Person) =
person.age > 18 && person.name.startsWith("A") && person.isActive
list.filter(::isEligible)
9.3 使用尾随 Lambda #
kotlin
// 推荐
list.map { it * 2 }
// 不推荐
list.map({ it * 2 })
十、总结 #
Lambda 要点:
| 特性 | 说明 |
|---|---|
| 语法 | { 参数 -> 函数体 } |
| it | 单参数隐式名称 |
| 尾随 Lambda | 放在括号外 |
| 闭包 | 捕获外部变量 |
| 函数引用 | ::functionName |
下一步,让我们学习 高阶函数!
最后更新:2026-03-27