Kotlin 学习手册01 高阶函数
- 1 函数作为参数
- 2 函数作为返回值
- 3 测试代码
在Kotlin中,高阶函数(Higher-Order Functions)是指接受函数作为参数或返回一个函数的函数。这种特性允许你将函数像变量一样传递,从而使代码更加灵活和可重用。
1 函数作为参数
/*** 函数作为参数*/
fun calculate(x: Int, y: Int, operation: (Int, Int) -> Int): Int {return operation(x, y)
}
2 函数作为返回值
/*** 函数作为返回值*/
fun operation(operation: String): (Int, Int) -> Int {return when (operation) {"addition" -> { a, b -> addition(a, b) }"subtraction" -> { a, b -> subtraction(a, b) }"multiply" -> { a, b -> a * b }"division" -> { a, b -> a / b }else -> { _, _ -> 0 }}
}
3 测试代码
/*** 加法*/
fun addition(a: Int, b: Int): Int = a + b/*** 减法*/
fun subtraction(a: Int, b: Int): Int = a - b/*** 乘法*/
fun multiply(a: Int, b: Int): Int {return a * b
}/*** 除法*/
fun division(a: Int, b: Int): Int {return a / b
}fun main() {// 函数作为参数println(calculate(5, 3, ::addition))println(calculate(5, 3, ::subtraction))println(calculate(5, 3, ::multiply))println(calculate(5, 3, ::division))// 函数作为返回值println(operation("addition")(5, 3))println(operation("subtraction")(5, 3))println(operation("multiply")(5, 3))println(operation("division")(5, 3))
}