Kotlin函数定义
外观
Kotlin函数定义[编辑 | 编辑源代码]
Kotlin函数是执行特定任务的代码块,可以接收输入参数并返回结果。函数是Kotlin语言的核心组成部分,支持多种定义方式和高级特性。
基本语法[编辑 | 编辑源代码]
Kotlin使用fun
关键字定义函数,基本结构如下:
fun functionName(parameters: ParameterType): ReturnType {
// 函数体
return result
}
无参数函数示例[编辑 | 编辑源代码]
fun greet(): String {
return "Hello, World!"
}
fun main() {
println(greet()) // 输出: Hello, World!
}
带参数函数示例[编辑 | 编辑源代码]
fun add(a: Int, b: Int): Int {
return a + b
}
fun main() {
println(add(5, 3)) // 输出: 8
}
函数组件详解[编辑 | 编辑源代码]
1. 参数[编辑 | 编辑源代码]
Kotlin支持:
- 默认参数
- 命名参数
- 可变参数
fun printInfo(name: String, age: Int = 25, vararg hobbies: String) {
println("Name: $name, Age: $age")
hobbies.forEach { println("Hobby: $it") }
}
fun main() {
printInfo("Alice") // 使用默认age
printInfo("Bob", 30, "Reading", "Swimming") // 传递可变参数
printInfo(name = "Charlie", age = 28) // 命名参数
}
2. 返回类型[编辑 | 编辑源代码]
- 显式声明:
: ReturnType
- 类型推断:单表达式函数可省略返回类型
// 显式声明
fun square(x: Int): Int {
return x * x
}
// 类型推断
fun cube(x: Int) = x * x * x
函数类型[编辑 | 编辑源代码]
Kotlin函数可分为以下几类:
1. 成员函数[编辑 | 编辑源代码]
定义在类或对象内部:
class Calculator {
fun add(a: Int, b: Int): Int = a + b
}
2. 顶层函数[编辑 | 编辑源代码]
直接定义在文件中:
// 文件: MathUtils.kt
fun factorial(n: Int): Long {
return if (n <= 1) 1 else n * factorial(n - 1)
}
3. 局部函数[编辑 | 编辑源代码]
在另一个函数内部定义:
fun outerFunction() {
fun innerFunction() {
println("内部函数")
}
innerFunction()
}
4. 扩展函数[编辑 | 编辑源代码]
为现有类添加新功能:
fun String.addExclamation(): String = "$this!"
fun main() {
println("Hello".addExclamation()) // 输出: Hello!
}
高级特性[编辑 | 编辑源代码]
1. 高阶函数[编辑 | 编辑源代码]
接收函数作为参数或返回函数:
fun calculate(x: Int, y: Int, operation: (Int, Int) -> Int): Int {
return operation(x, y)
}
fun main() {
val result = calculate(10, 5) { a, b -> a * b }
println(result) // 输出: 50
}
2. Lambda表达式[编辑 | 编辑源代码]
匿名函数的简洁写法:
val sum = { x: Int, y: Int -> x + y }
println(sum(2, 3)) // 输出: 5
3. 中缀表示法[编辑 | 编辑源代码]
适用于单参数成员函数或扩展函数:
infix fun Int.times(str: String) = str.repeat(this)
fun main() {
println(2 times "Bye ") // 输出: Bye Bye
}
数学函数示例[编辑 | 编辑源代码]
计算两点间距离的函数:
Kotlin实现:
import kotlin.math.sqrt
import kotlin.math.pow
fun distance(x1: Double, y1: Double, x2: Double, y2: Double): Double {
return sqrt((x2 - x1).pow(2) + (y2 - y1).pow(2))
}
fun main() {
println(distance(0.0, 0.0, 3.0, 4.0)) // 输出: 5.0
}
实际应用案例[编辑 | 编辑源代码]
电商系统价格计算函数:
fun calculateTotal(
basePrice: Double,
discount: Double = 0.0,
taxRate: Double = 0.1,
applyCoupon: (Double) -> Double = { it }
): Double {
val discounted = basePrice * (1 - discount)
val couponApplied = applyCoupon(discounted)
return couponApplied * (1 + taxRate)
}
fun main() {
val total = calculateTotal(100.0, 0.2) { price ->
if (price > 50) price - 10 else price
}
println("总价: $$total") // 输出示例: 总价: $99.0
}
最佳实践[编辑 | 编辑源代码]
1. 使用描述性函数名 2. 保持函数简短(建议不超过20行) 3. 遵循单一职责原则 4. 合理使用默认参数减少重载 5. 对于复杂逻辑,考虑分解为多个小函数
常见错误[编辑 | 编辑源代码]
- 忘记返回类型(非单表达式函数)
- 参数类型不匹配
- 混淆
Unit
与空返回 - 可变参数位置错误(必须是最后一个参数)
// 错误示例
fun problematic(a: Int, vararg b: String, c: Double) { ... } // 编译错误
性能考虑[编辑 | 编辑源代码]
- 内联函数(
inline
)适合高阶函数,可减少运行时开销 - 避免在循环中创建大量临时lambda
- 尾递归函数(
tailrec
)优化递归性能
tailrec fun factorial(n: Int, acc: Long = 1): Long {
return if (n <= 1) acc else factorial(n - 1, n * acc)
}
总结[编辑 | 编辑源代码]
Kotlin函数提供了强大而灵活的方式来组织代码,从简单的工具函数到复杂的高阶函数,支持多种编程范式。掌握函数定义是成为Kotlin开发者的基础,也是理解更高级语言特性的关键。