局部函数
6.2 局部函数
核心定义:定义在其他函数内部的函数;
使用场景:封装函数内部的重复逻辑,避免暴露给外部;
示例:
fun calculateTotal(prices: List<Double>): Double { // 局部函数:仅在calculateTotal内部可用 fun validatePrice(price: Double): Boolean { return price >= 0 } var total = 0.0 prices.forEach { if (validatePrice(it)) { total += it } } return total } fun main() { println(calculateTotal(listOf(10.0, 20.0, -5.0))) // 30.0 }