Kotlin 从入门到进阶 之函数模块(核心基础)(二)

Kotlin 函数模块

1. 普通函数

kotlin 复制代码
// 标准函数声明
fun sum(a: Int, b: Int): Int {
    return a + b
}

// 单表达式函数(省略花括号)
fun multiply(a: Int, b: Int) = a * b

// 无返回值(Unit 可省略)
fun printSum(a: Int, b: Int) {
    println("Result: ${a + b}")
}

fun greet(name: String): Unit {
    println("Hello, $name")
}

2. 默认参数

kotlin 复制代码
// 默认参数值,无需重载
fun configure(
    name: String,
    timeout: Int = 3000,
    retry: Boolean = false
) {
    println("$name, timeout=$timeout, retry=$retry")
}

configure("API")                      // 使用默认 timeout 和 retry
configure("API", 5000)               // 自定义 timeout
configure("API", retry = true)       // 具名参数,跳过 timeout

3. 具名参数

kotlin 复制代码
// 具名参数:可读性高,可任意顺序传参
fun createUser(
    name: String,
    age: Int,
    email: String = "default@example.com",
    isActive: Boolean = true
) {}

// 全具名调用
createUser(
    name = "windCloud",
    age = 25,
    email = "wind@example.com",
    isActive = false
)

// 混合:位置参数 + 具名参数(具名参数后不允许再有位置参数)
createUser("windCloud", age = 25, isActive = false)

4. Unit 与无返回值

kotlin 复制代码
// Unit 省略时,编译器自动推断
fun logMessage(msg: String) {        // 返回类型实为 Unit
    println(msg)
}

// 显式声明
fun logMessageExplicit(msg: String): Unit {
    println(msg)
}

// Nothing:无正常返回(用于表示程序终止或异常)
fun fail(message: String): Nothing {
    throw IllegalArgumentException(message)
}

5. 扩展函数 / 扩展属性(Android 常用)

kotlin 复制代码
// 扩展函数:为已有类添加新方法
fun String.addExclamation() = "$this!"

fun String.repeat(n: Int): String {
    return (1..n).joinToString("") { this }
}

// 使用
"Hello".addExclamation()             // "Hello!"
"ab".repeat(3)                        // "ababab"

// 扩展属性
val String.lastChar: Char
    get() = this[length - 1]

val "Kotlin".lastChar                 // 'n'

// 可空扩展(this 为可空)
fun String?.orEmpty(): String {
    return this ?: ""
}

val nullString: String? = null
nullString.orEmpty()                  // ""

// Android 示例:View 扩展
fun View.hideKeyboard() {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(windowToken, 0)
}

fun EditText.showKeyboard() {
    requestFocus()
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}

6. 局部函数 / 嵌套函数

kotlin 复制代码
// 局部函数:函数内部定义的函数
fun processData(raw: String): String {
    fun trimPrefix(prefix: String): String {
        return raw.removePrefix(prefix)
    }

    fun validate(content: String): Boolean {
        return content.isNotEmpty() && content.length > 2
    }

    val trimmed = trimPrefix("DATA:")
    return if (validate(trimmed)) trimmed else raw
}

// 嵌套函数:访问外层函数变量
fun outer(x: Int): Int {
    var result = x

    fun inner(y: Int): Int {
        result += y
        return result
    }

    return inner(10)
}

outer(5)                              // 15

7. 高阶函数基础 / 函数引用 ::

kotlin 复制代码
// 高阶函数:接收或返回函数的函数
fun operate(a: Int, b: Int, op: (Int, Int) -> Int): Int {
    return op(a, b)
}

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

// 函数引用 ::
fun maxInt(a: Int, b: Int) = if (a > b) a else b

operate(10, 5, ::maxInt)               // 10

// 内联函数(减少运行时开销)
inline fun measure(block: () -> Unit) {
    val start = System.currentTimeMillis()
    block()
    println("Took ${System.currentTimeMillis() - start}ms")
}

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

val double = multiplier(2)
val triple = multiplier(3)

double(5)                             // 10
triple(5)                             // 15

// 组合函数
fun <A, B, C> compose(f: (B) -> C, g: (A) -> B): (A) -> C {
    return { x -> f(g(x)) }
}

val square = { x: Int -> x * x }
val toString = { x: Int -> x.toString() }

val squareToString = compose(::toString, ::square)
squareToString(4)                     // "16"

8. 常用标准高阶函数

kotlin 复制代码
// let:空安全 + 转换
val len = "Kotlin".let { it.length }  // 6

// run:对象上执行块
val result = "  run  ".run {
    this.trim().uppercase()
}                                     // "RUN"

// with:调用多个方法(不推荐,语义不明)
val info = with(StringBuilder()) {
    append("Kotlin")
    append(" 1.9")
    toString()
}                                     // "Kotlin 1.9"

// apply:配置对象
val person = Person().apply {
    name = "windCloud"
    age = 25
}

// also:额外操作
val list = mutableListOf(1, 2, 3).also {
    println("Created: $it")
}

// map / filter / reduce
listOf(1, 2, 3, 4, 5)
    .map { it * 2 }                    // [2, 4, 6, 8, 10]
    .filter { it > 5 }                 // [6, 8, 10]
    .reduce { acc, num -> acc + num }   // 24

快速对照表

概念 示例 用途
默认参数 fun f(x: Int = 10) 减少重载
具名参数 f(y = 5) 可读性 + 自由顺序
扩展函数 fun String.add() 为已有类添加方法
扩展属性 val String.last 为已有类添加属性
局部函数 函数内再定义函数 封装辅助逻辑
高阶函数 op: (Int, Int) -> Int 接收函数参数
函数引用 ::maxInt 传递函数引用
内联 inline fun 减少运行时开销
相关推荐
迈巴赫车主11 小时前
蓝桥杯21247弹跳鞋java
java·开发语言·数据结构·算法·职场和发展·蓝桥杯
SoftLipaRZC11 小时前
C语言数据在内存中的存储:整型与浮点型的秘密
c语言·开发语言
悟乙己11 小时前
python DoWhy 库使用案例: SaaS 公司的客服案例
开发语言·python
就叫_这个吧11 小时前
JavaScript基础数据类型、运算符、数组、函数的定义及DOM方式应用
开发语言·前端·javascript
basketball61611 小时前
Golang:基本输入输出使用方法总结
开发语言·golang·xcode
随遇丿而安11 小时前
第6周:RecyclerView 真正难的不是“写个列表”,而是让列表在复用中保持正确
android
Shingmc311 小时前
【Linux】多路转接之epoll
linux·运维·服务器·开发语言·网络
utf8mb4安全女神11 小时前
⽇志管理与深层防⽕墙
java·开发语言·spring boot
Mr.Lu ‍11 小时前
QT调试查看QT内部数据时显示无可用信息,未为 Qt5Cored.dll 加载任何符号
开发语言·qt
qq_4523962311 小时前
第九篇:《Dockerfile 指令精讲(二):WORKDIR、ENV、ARG、EXPOSE》
java·开发语言·docker