kotlin lambda编程

Kotlin 的 Lambda(匿名函数)是函数式编程的核心特性之一,允许你以简洁的方式编写代码,尤其适用于集合操作、回调、DSL(领域特定语言)等场景。

1. Lambda 表达式基础

Lambda 表达式是一个匿名函数,语法如下:

1
2
val sum: (Int, Int) -> Int = { a, b -> a + b }
println(sum(2, 3)) // 输出 5

语法说明

  • { 参数1, 参数2 -> 函数体 }
  • val sum: (Int, Int) -> Int 明确声明了函数类型,表示它接收两个 Int 并返回 Int

2. 使用 it 关键字

当 Lambda 只有一个参数时,可以用 it 代替参数名:

1
2
val square: (Int) -> Int = { it * it }
println(square(4)) // 输出 16

3. Lambda 作为函数参数

Lambda 可以作为参数传递给函数:

1
2
3
4
5
6
fun operateOnNumbers(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
return operation(a, b)
}

val result = operateOnNumbers(4, 5) { x, y -> x * y }
println(result) // 输出 20

4. 高阶函数 结合 Lambda

Kotlin 支持高阶函数(即参数或返回值是函数的函数):

1
2
3
4
5
fun higherOrderFunction(operation: () -> Unit) {
operation()
}

higherOrderFunction { println("Hello, Lambda!") }

5. 在集合操作中的应用

Lambda 在 Kotlin 的集合 API 中应用广泛,如 mapfilterreduce

1
2
3
4
5
6
val numbers = listOf(1, 2, 3, 4, 5)
val squaredNumbers = numbers.map { it * it }
println(squaredNumbers) // 输出 [1, 4, 9, 16, 25]

val evenNumbers = numbers.filter { it % 2 == 0 }
println(evenNumbers) // 输出 [2, 4]

6. letapplyrunwithalso

Kotlin 提供了一系列作用域函数,结合 Lambda 使用非常强大:

1
2
3
4
5
val name: String? = "Kotlin"
name?.let { println(it.uppercase()) } // 非空时执行

val person = Person("John").apply { age = 30 } // apply 适用于修改对象属性
println(person)

7. 闭包(Closure)

Lambda 表达式可以访问外部变量:

1
2
3
4
5
6
7
8
9
fun counter(): () -> Int {
var count = 0
return { count++ }
}

val next = counter()
println(next()) // 0
println(next()) // 1
println(next()) // 2

8. 带 return 的 Lambda

Lambda 默认返回最后一行的值,如果需要提前返回,可以使用 return@label

1
2
3
4
listOf(1, 2, 3, 4, 5).forEach { 
if (it == 3) return@forEach
println(it)
}