Kotlin 高阶函数 #

一、高阶函数概述 #

高阶函数是指:

  • 接收函数作为参数的函数
  • 返回函数的函数
  • 或两者兼有

二、函数作为参数 #

2.1 基本语法 #

kotlin
fun operate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
    return operation(a, b)
}

2.2 调用方式 #

kotlin
// 使用 Lambda
operate(10, 5) { x, y -> x + y }  // 15
operate(10, 5) { x, y -> x * y }  // 50

// 使用函数引用
fun add(a: Int, b: Int) = a + b
operate(10, 5, ::add)  // 15

// 使用匿名函数
operate(10, 5, fun(a, b) = a - b)  // 5

2.3 实际应用 #

kotlin
fun processList(
    list: List<Int>,
    filter: (Int) -> Boolean,
    transform: (Int) -> Int
): List<Int> {
    return list.filter(filter).map(transform)
}

val result = processList(
    list = listOf(1, 2, 3, 4, 5),
    filter = { it > 2 },
    transform = { it * 2 }
)
// [6, 8, 10]

三、函数作为返回值 #

3.1 返回函数 #

kotlin
fun getOperation(type: String): (Int, Int) -> Int {
    return when (type) {
        "add" -> { a, b -> a + b }
        "subtract" -> { a, b -> a - b }
        "multiply" -> { a, b -> a * b }
        "divide" -> { a, b -> a / b }
        else -> { _, _ -> 0 }
    }
}

val add = getOperation("add")
add(10, 5)  // 15

3.2 工厂函数 #

kotlin
fun createValidator(minLength: Int): (String) -> Boolean {
    return { input -> input.length >= minLength }
}

val validateName = createValidator(3)
val validatePassword = createValidator(8)

validateName("Kotlin")     // true
validateName("Go")         // false
validatePassword("12345678")  // true

3.3 柯里化 #

kotlin
fun add(a: Int): (Int) -> Int {
    return { b -> a + b }
}

val addFive = add(5)
addFive(10)  // 15
addFive(20)  // 25

// 直接调用
add(5)(10)  // 15

四、常用高阶函数 #

4.1 let #

kotlin
// 空安全处理
val name: String? = "Kotlin"
val length = name?.let {
    println(it)
    it.length
}

// 作用域限制
val result = data.let { d ->
    // 处理 d
    process(d)
}

4.2 run #

kotlin
// 执行代码块并返回结果
val result = run {
    val a = 10
    val b = 20
    a + b
}

// 对象的 run
val person = Person("Kotlin", 10)
val info = person.run {
    "$name is $age years old"
}

4.3 with #

kotlin
val person = Person("Kotlin", 10)

val result = with(person) {
    println(name)
    println(age)
    "Processed: $name"
}

4.4 apply #

kotlin
// 配置对象
val person = Person().apply {
    name = "Kotlin"
    age = 10
}

// Builder 模式
val config = Configuration().apply {
    host = "localhost"
    port = 8080
    ssl = true
}

4.5 also #

kotlin
// 附加操作
val numbers = mutableListOf(1, 2, 3)
    .also { println("Creating list: $it") }
    .apply { add(4) }
    .also { println("After adding: $it") }

4.6 takeIf / takeUnless #

kotlin
val input = "Kotlin"

val result = input.takeIf { it.length > 3 }
    ?.uppercase()  // "KOTLIN"

val result2 = input.takeUnless { it.isBlank() }
    ?.lowercase()  // "kotlin"

五、集合高阶函数 #

5.1 map 系列 #

kotlin
val list = listOf(1, 2, 3, 4, 5)

// map
list.map { it * 2 }  // [2, 4, 6, 8, 10]

// mapNotNull
list.mapNotNull { if (it > 2) it * 2 else null }  // [6, 8, 10]

// mapIndexed
list.mapIndexed { index, value -> "[$index] = $value" }
// ["[0] = 1", "[1] = 2", ...]

5.2 filter 系列 #

kotlin
val list = listOf(1, 2, 3, 4, 5, 6)

// filter
list.filter { it % 2 == 0 }  // [2, 4, 6]

// filterNot
list.filterNot { it % 2 == 0 }  // [1, 3, 5]

// filterIndexed
list.filterIndexed { index, _ -> index % 2 == 0 }  // [1, 3, 5]

// filterIsInstance
val mixed: List<Any> = listOf(1, "a", 2, "b", 3)
mixed.filterIsInstance<String>()  // ["a", "b"]

5.3 reduce / fold #

kotlin
val list = listOf(1, 2, 3, 4, 5)

// reduce
list.reduce { acc, n -> acc + n }  // 15

// fold(带初始值)
list.fold(0) { acc, n -> acc + n }  // 15
list.fold(10) { acc, n -> acc + n }  // 25

// foldRight
list.foldRight(0) { n, acc -> acc + n }  // 15

5.4 分组与分区 #

kotlin
val list = listOf(1, 2, 3, 4, 5, 6)

// groupBy
list.groupBy { if (it % 2 == 0) "even" else "odd" }
// {odd=[1, 3, 5], even=[2, 4, 6]}

// partition
val (evens, odds) = list.partition { it % 2 == 0 }
// evens = [2, 4, 6], odds = [1, 3, 5]

// chunked
list.chunked(2)  // [[1, 2], [3, 4], [5, 6]]

5.5 排序 #

kotlin
data class Person(val name: String, val age: Int)

val people = listOf(
    Person("Bob", 30),
    Person("Alice", 25),
    Person("Charlie", 35)
)

// sortBy
people.sortedBy { it.age }
// [Person(Alice, 25), Person(Bob, 30), Person(Charlie, 35)]

// sortedWith
people.sortedWith(compareBy({ it.age }, { it.name }))

// sortedByDescending
people.sortedByDescending { it.age }

5.6 查找 #

kotlin
val list = listOf(1, 2, 3, 4, 5)

// find / firstOrNull
list.find { it > 3 }  // 4
list.firstOrNull { it > 10 }  // null

// lastOrNull
list.lastOrNull { it < 4 }  // 3

// indexOfFirst / indexOfLast
list.indexOfFirst { it > 2 }  // 2

六、作用域函数选择 #

函数 对象引用 返回值 用途
let it Lambda 结果 空检查、转换
run this Lambda 结果 初始化、计算
with this Lambda 结果 操作对象
apply this 对象本身 配置对象
also it 对象本身 附加操作
kotlin
// let:空安全处理
name?.let { println(it) }

// run:计算
val result = run { a + b }

// with:操作对象
with(person) {
    name = "New"
    age = 20
}

// apply:配置
val config = Config().apply {
    host = "localhost"
}

// also:日志、验证
list.also { println("Size: ${it.size}") }

七、实战示例 #

7.1 数据处理管道 #

kotlin
data class Order(val id: Int, val amount: Double, val status: String)

val orders = listOf(
    Order(1, 100.0, "completed"),
    Order(2, 50.0, "pending"),
    Order(3, 200.0, "completed"),
    Order(4, 75.0, "cancelled")
)

val totalCompleted = orders
    .filter { it.status == "completed" }
    .map { it.amount }
    .reduce { acc, amount -> acc + amount }
// 300.0

7.2 链式验证 #

kotlin
fun validate(input: String): Result<String> {
    return input
        .takeIf { it.isNotBlank() }
        ?.let { it.trim() }
        ?.takeIf { it.length >= 3 }
        ?.let { Result.success(it) }
        ?: Result.failure(IllegalArgumentException("Invalid input"))
}

7.3 构建器模式 #

kotlin
class QueryBuilder {
    private var table: String = ""
    private var columns: List<String> = listOf("*")
    private var where: String = ""
    
    fun from(table: String) = apply { this.table = table }
    fun select(vararg columns: String) = apply { this.columns = columns.toList() }
    fun where(condition: String) = apply { this.where = condition }
    
    fun build(): String {
        return buildString {
            append("SELECT ${columns.joinToString()}")
            append(" FROM $table")
            if (where.isNotEmpty()) append(" WHERE $where")
        }
    }
}

val query = QueryBuilder()
    .select("name", "age")
    .from("users")
    .where("age > 18")
    .build()
// SELECT name, age FROM users WHERE age > 18

八、最佳实践 #

8.1 选择合适的作用域函数 #

kotlin
// 需要返回对象本身 → apply / also
val config = Config().apply { host = "localhost" }

// 需要返回计算结果 → let / run / with
val result = data.run { process() }

// 空安全处理 → let
name?.let { process(it) }

8.2 避免嵌套过深 #

kotlin
// 不推荐
list.filter { ... }
    .map { ... }
    .filter { ... }
    .map { ... }
    .filter { ... }

// 推荐:提取中间变量或函数
val filtered = list.filter { ... }.map { ... }
val processed = filtered.filter { ... }.map { ... }

九、总结 #

高阶函数要点:

  1. 函数作为参数:灵活的行为传递
  2. 函数作为返回值:工厂模式、柯里化
  3. 作用域函数:let、run、with、apply、also
  4. 集合操作:map、filter、reduce、groupBy

下一步,让我们学习 扩展函数

最后更新:2026-03-27