// 标准函数声明
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")
}
// 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