Android Kotlin 中常用函数特性和技巧
Kotlin 是现代 JVM 开发语言,强调函数式编程与高阶抽象。
通过函数、Lambda 和扩展特性,Kotlin 可以让代码更简洁、可读性更高、逻辑封装更清晰。本文整理了 Kotlin 中常用的函数特性和实用技巧,并配上示例,方便快速学习和参考。
1.Kotlin 高级函数特性总览
Kotlin 是现代 JVM 开发语言,强调函数式编程与高阶抽象。
通过函数、Lambda 和扩展特性,Kotlin 可以让代码更简洁、可读性更高、逻辑封装更清晰。
| 类型/特性 | 作用/特点 | 常见场景 | 示例 |
|---|---|---|---|
| 高阶函数 | 接受函数作为参数或返回值为函数 | 回调、异步处理、集合操作 | list.filter { it > 0 } |
内联函数 (inline) | 避免函数调用开销,减少 Lambda 产生的对象 | 高频调用、内存优化 | inline fun runTask(action: () -> Unit) { action() } |
| 扩展函数 | 给已有类添加方法而无需继承 | 工具方法、API增强 | fun String.md5(): String = ... |
| 扩展属性 | 给已有类添加属性 | Android View 扩展、配置增强 | val Context.screenWidth: Int get() = resources.displayMetrics.widthPixels |
中缀函数 (infix) | 使函数调用更简洁,像运算符一样 | DSL、简化语法 | infix fun Int.times(str: String) = str.repeat(this) |
尾递归函数 (tailrec) | 优化递归为迭代,避免栈溢出 | 算法、深度递归 | tailrec fun factorial(n: Int, acc: Int = 1): Int = if (n <= 1) acc else factorial(n - 1, n * acc) |
| 局部函数 | 在函数内部定义函数,增强封装 | 避免重复代码、逻辑拆分 | fun process() { fun validate() { ... }; validate() } |
| 具名参数/默认参数 | 提高可读性、减少重载 | 配置函数、构造器优化 | fun connect(host: String, port: Int = 80) |
| Lambda 表达式 | 简化函数实现,支持闭包 | 回调、集合操作、协程 | { x, y -> x + y } |
| 匿名函数 | 和 Lambda 类似,但更灵活 | 多个 return 场景 | fun(x: Int, y: Int): Int = x + y |
生成序列 (sequence) | 惰性计算,处理大数据流 | 大集合、懒加载 | sequence { yieldAll(1..10) } |
| 操作符重载 | 自定义运算符行为 | DSL、数学计算 | operator fun Point.plus(other: Point): Point |
2.函数介绍以及函数的示例
1️⃣ 高阶函数(Higher-Order Function)
作用:接收函数作为参数或返回函数,实现回调和动态行为。
适用场景:集合操作(filter/map)、异步处理、回调封装。
示例:
fun <T> List<T>.customFilter(predicate: (T) -> Boolean): List<T> {
val result = mutableListOf<T>()
for (item in this) {
if (predicate(item)) result.add(item)
}
return result
}
val nums = listOf(1, -2, 3, 0)
println(nums.customFilter { it > 0 }) // 输出: [1, 3]
2️⃣ 内联函数(inline)
作用:在编译时将函数体插入调用处,减少 Lambda 对象创建和函数调用开销。
适用场景:高频调用函数、性能敏感的回调。
示例:
inline fun measureTime(action: () -> Unit) {
val start = System.currentTimeMillis()
action()
println("Time: ${System.currentTimeMillis() - start}ms")
}
measureTime { Thread.sleep(100) }
3️⃣ 扩展函数与扩展属性
作用:给已有类添加方法或属性,无需继承。
适用场景:工具方法、API 增强、Android View 扩展。
示例:
fun String.md5(): String = this.toByteArray().joinToString("") { "%02x".format(it) }
val String.firstChar: Char
get() = this[0]
println("Hello".md5())
println("Hello".firstChar) // 输出: H
4️⃣ 中缀函数(infix)
作用:让函数调用像自然语言或运算符。
适用场景:DSL、简化语法。
示例:
infix fun Int.times(str: String) = str.repeat(this)
println(3 times "Hi ") // 输出: Hi Hi Hi
5️⃣ 尾递归函数(tailrec)
作用:优化递归为迭代,防止栈溢出。
适用场景:算法实现、深度递归。
示例:
tailrec fun factorial(n: Int, acc: Int = 1): Int =
if (n <= 1) acc else factorial(n - 1, n * acc)
println(factorial(5)) // 输出: 120
6️⃣ 局部函数
作用:在函数内部定义函数,增强封装。
适用场景:避免重复代码、拆分逻辑、控制作用域。
示例:
fun process(input: String): String {
fun sanitize(s: String) = s.trim().lowercase()
return sanitize(input)
}
println(process(" Kotlin ")) // 输出: kotlin
7️⃣ 具名参数与默认参数
作用:函数调用可显式指定参数名,参数可有默认值。
适用场景:构造器配置、函数调用简化。
示例:
fun connect(host: String, port: Int = 80) = println("Connecting to $host:$port")
connect("example.com") // 输出: Connecting to example.com:80
connect(host = "example.com", port = 443) // 输出: Connecting to example.com:443
8️⃣ Lambda 表达式与匿名函数
作用:简化函数实现,支持闭包。
适用场景:回调、集合操作、协程。
示例:
val sumLambda: (Int, Int) -> Int = { x, y -> x + y }
val sumAnonymous = fun(x: Int, y: Int): Int = x + y
println(sumLambda(2, 3)) // 输出: 5
println(sumAnonymous(2, 3)) // 输出: 5
9️⃣ 生成序列(sequence)
作用:惰性计算大数据流。
适用场景:处理大集合、懒加载。
示例:
val seq = sequence { for (i in 1..5) yield(i * i) }
println(seq.toList()) // 输出: [1, 4, 9, 16, 25]
🔟 操作符重载
作用:自定义类的运算符行为。
适用场景:DSL、数学计算。
示例:
data class Point(val x: Int, val y: Int) {
operator fun plus(other: Point) = Point(x + other.x, y + other.y)
}
val p1 = Point(1, 2)
val p2 = Point(3, 4)
println(p1 + p2) // 输出: Point(x=4, y=6)
总结
- Kotlin 高级函数特性不仅是语法糖,更是提升代码优雅性、可维护性和性能的核心手段。
- 高阶函数、Lambda、扩展、尾递归等特性组合使用,可以写出函数式、可组合、可读性强的 Kotlin 代码。