Kotlin 中的函数是执行特定任务的代码块,它是 Kotlin 编程的基本构建块之一。下面我将详细介绍 Kotlin 函数的各个方面。

1. 函数的基本语法

Kotlin 使用 fun 关键字声明函数:

fun functionName(parameters: ParameterType): ReturnType {
    // 函数体
    return result
}

示例:

fun add(a: Int, b: Int): Int {
    return a + b
}

2. 函数类型

2.1 成员函数

定义在类或对象内部的函数:

class Sample {
    fun memberFunction() {
        println("这是成员函数")
    }
}

2.2 顶层函数

直接定义在文件中的函数,不属于任何类:

// 在文件 TopLevel.kt 中
fun topLevelFunction() {
    println("这是顶层函数")
}

2.3 局部函数

函数内部定义的函数:

fun outerFunction() {
    fun localFunction() {
        println("这是局部函数")
    }
    localFunction()
}

2.4 扩展函数

为现有类添加新功能而不继承它:

fun String.addExclamation(): String {
    return "$this!"
}

// 使用
val str = "Hello".addExclamation()  // "Hello!"

3. 函数参数

3.1 默认参数

Kotlin 支持为参数提供默认值:

fun greet(name: String = "World") {
    println("Hello, $name!")
}

greet()          // 输出: Hello, World!
greet("Kotlin")  // 输出: Hello, Kotlin!

3.2 命名参数

调用函数时可以指定参数名:

fun createUser(name: String, age: Int, isAdmin: Boolean = false) {
    // ...
}

// 调用
createUser(age = 25, name = "Alice")

3.3 可变数量参数 (vararg)

使用 vararg 关键字表示可以接受任意数量的参数:

fun sum(vararg numbers: Int): Int {
    return numbers.sum()
}

sum(1, 2, 3)  // 6
sum(1, 2, 3, 4, 5)  // 15

4. 返回值

4.1 显式返回值

fun max(a: Int, b: Int): Int {
    return if (a > b) a else b
}

4.2 单表达式函数

当函数体只有单个表达式时,可以简写:

fun max(a: Int, b: Int): Int = if (a > b) a else b

4.3 无返回值 (Unit)

不返回值的函数返回 Unit 类型,可以省略:

fun printMessage(message: String): Unit {
    println(message)
}
// 等价于
fun printMessage(message: String) {
    println(message)
}

5. 高阶函数

高阶函数是将函数作为参数或返回值的函数:

// 接收函数作为参数
fun calculate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
    return operation(a, b)
}

// 返回函数的函数
fun getOperation(type: String): (Int, Int) -> Int {
    return when (type) {
        "add" -> { a, b -> a + b }
        "subtract" -> { a, b -> a - b }
        else -> { a, b -> a * b }
    }
}

// 使用
val result = calculate(5, 3) { x, y -> x + y }  // 8
val operation = getOperation("add")
operation(5, 3)  // 8

6. Lambda 表达式

Lambda 是匿名函数的简写形式:

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

// 作为参数
listOf(1, 2, 3).forEach { item -> println(item) }

7. 内联函数

使用 inline 关键字可以减少高阶函数的运行时开销:

inline fun measureTime(block: () -> Unit) {
    val start = System.currentTimeMillis()
    block()
    println("执行时间: ${System.currentTimeMillis() - start} ms")
}

measureTime {
    // 要测量时间的代码
}

8. 中缀函数

使用 infix 关键字可以创建中缀表示法的函数:

infix fun Int.times(str: String): String = str.repeat(this)

// 使用
println(3 times "Hello ")  // 输出: Hello Hello Hello 

9. 尾递归函数

使用 tailrec 关键字优化递归函数,避免栈溢出:

tailrec fun factorial(n: Int, acc: Int = 1): Int = 
    if (n <= 1) acc else factorial(n - 1, n * acc)

println(factorial(5))  // 120

10. 作用域函数

Kotlin 提供了一系列作用域函数:letrunwithapplyalso

val str = "Hello"

str.let {
    println(it.length)  // 5
    it.toUpperCase()
}

str.run {
    println(length)  // 5
    toUpperCase()
}

with(str) {
    println(length)  // 5
    toUpperCase()
}

str.apply {
    println(length)  // 5
    toUpperCase()  // 返回值是str本身
}

str.also {
    println(it.length)  // 5
    it.toUpperCase()  // 返回值是str本身
}

11. 泛型函数

fun <T> singletonList(item: T): List<T> {
    return listOf(item)
}

val list = singletonList(1)  // List<Int>

12. 运算符重载

通过特定名称的函数重载运算符:

data class Point(val x: Int, val y: Int) {
    operator fun plus(other: Point): Point {
        return 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 的函数系统非常强大且灵活,提供了多种特性来简化代码编写和提高表达力。从基本的函数定义到高阶函数、扩展函数、作用域函数等高级特性,Kotlin 的函数设计使得代码更加简洁、安全和易于维护。

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐