技术文档中心
首页
React
Vue
TypeScript
Kotlin
React Native
Electron
Android
首页
React
Vue
TypeScript
Kotlin
React Native
Electron
Android
  • 基础入门

    • Kotlin 教程
    • 快速开始
    • 基础语法
    • 变量与类型
    • 控制流
    • 函数
  • 面向对象

    • 类与对象
  • 高级特性

    • 泛型
    • 集合操作
    • 协程

函数

函数声明

// 基本函数
fun greet(name: String): String {
    return "Hello, $name!"
}

// 表达式函数
fun sum(a: Int, b: Int) = a + b

// 无返回值
fun printSum(a: Int, b: Int): Unit {
    println(a + b)
}

// Unit 可省略
fun printSum(a: Int, b: Int) {
    println(a + b)
}

参数

默认参数

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

greet()                    // Hello, Guest!
greet("Alice")             // Hello, Alice!
greet("Bob", "Hi")         // Hi, Bob!

命名参数

fun createUser(name: String, age: Int, email: String) {
    // ...
}

createUser(
    name = "Alice",
    age = 25,
    email = "alice@example.com"
)

// 混合使用
createUser("Bob", age = 30, email = "bob@example.com")

可变参数

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

sum(1, 2, 3, 4, 5)

// 展开数组
val nums = intArrayOf(1, 2, 3)
sum(*nums)

函数类型

// 函数类型变量
val operation: (Int, Int) -> Int = { a, b -> a + b }

// 使用
val result = operation(5, 3)  // 8

// 可空返回值
val nullable: (Int) -> Int? = { if (it > 0) it else null }

高阶函数

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

val sum = calculate(5, 3) { x, y -> x + y }
val product = calculate(5, 3) { x, y -> x * y }

// 返回函数
fun makeMultiplier(factor: Int): (Int) -> Int {
    return { number -> number * factor }
}

val double = makeMultiplier(2)
println(double(5))  // 10

Lambda 表达式

// 完整语法
val sum = { a: Int, b: Int -> a + b }

// 类型推断
val numbers = listOf(1, 2, 3, 4, 5)
val doubled = numbers.map { it * 2 }

// 多行 lambda
val result = numbers.filter {
    val isEven = it % 2 == 0
    isEven
}

// 最后一个参数是 lambda 可以移到括号外
numbers.forEach { println(it) }

// 下划线表示未使用的参数
val map = mapOf("a" to 1, "b" to 2)
map.forEach { _, value -> println(value) }

匿名函数

val sum = fun(a: Int, b: Int): Int {
    return a + b
}

// 表达式形式
val multiply = fun(a: Int, b: Int) = a * b

内联函数

inline fun measureTime(block: () -> Unit) {
    val start = System.currentTimeMillis()
    block()
    val end = System.currentTimeMillis()
    println("Time: ${end - start}ms")
}

measureTime {
    // 耗时操作
}

扩展函数

// 为 String 添加扩展
fun String.removeSpaces(): String {
    return this.replace(" ", "")
}

val text = "Hello World"
println(text.removeSpaces())  // HelloWorld

// 可空接收者
fun String?.isNullOrEmpty(): Boolean {
    return this == null || this.isEmpty()
}

中缀函数

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

val result = 3 times "Hello"  // HelloHelloHello

尾递归

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

println(factorial(5))  // 120

局部函数

fun processUser(user: User) {
    fun validate(value: String, fieldName: String) {
        if (value.isEmpty()) {
            throw IllegalArgumentException("$fieldName is empty")
        }
    }
    
    validate(user.name, "Name")
    validate(user.email, "Email")
}
最近更新: 2026/2/24 16:53
Contributors: hailong
Prev
控制流