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 减少运行时开销
相关推荐
鱼儿也有烦恼3 小时前
8 issues were found when checking AAR metadata:
android
HalvmånEver3 小时前
MySQL的索引
android·linux·数据库·学习·mysql
加号33 小时前
【Qt】 应用程序发布:依赖库拷贝与部署指南
开发语言·qt
('-')3 小时前
八股复习2:Java Array list和Linked list
java·开发语言
小黄人软件3 小时前
C++读写编辑CSV文件示例源码 用于数据导入导出,比Excel好使
开发语言·c++·excel
郭涤生4 小时前
C++各个版本的性能和安全性总结
开发语言·c++
wljy15 小时前
二、静态库的制作和使用
linux·c语言·开发语言·c++
道剑剑非道5 小时前
FFmpeg 6.0 实战:用 C++ 封装摄像头采集与 RTSP 推流
开发语言·c++·ffmpeg
天天进步20155 小时前
Python全栈项目实战:基于深度学习的语音合成(TTS)系统
开发语言·python·深度学习