[2023] Kotlin Tutorial
Article directory
Part II Object Oriented and Functional Programming
Chapter 13 The Cornerstone of Functional Programming—Higher-order Functions and Lambda Expressions
Although the idea of functional programming is as old as object-oriented, the computer language that supports functional programming is only a matter of recent years. These languages include Swift, Python, Java 8, and C++ 11. As a new language, Kotlin also supports functional programming.
13.2 Higher-order functions
The key to functional programming is the support of higher-order functions. A function can be used as a parameter of another function, or return a value, then this function is a "higher-order function".
13.2.4 Using functions as parameters
A higher-order function can also receive another function as an argument. Let's look at an example of using a function as a parameter:
// 定义计算长方形面积的函数
// 函数类型(Double, Double) → Double
fun rectangleArea(width: Double, height: Double): Double {
return width * height;
}
// 定义计算三角形面积的函数
// 函数类型(Double, Double) → Double
fun triangleArea(bottom: Double, height: Double) = 0.5 * bottom * height
// 高阶函数, funName参数是函数类型
fun getAreaByFunc(funcName: (Double, Double) -> Double, a: Double, b: Double): Double {
return funcName(a, b)
}
fun main() {
// 获得计算三角形的面积函数
var result = getAreaByFunc(::triangleArea, 10.0, 15.0)
println("底10 高15的三角形面积为: $result")
// 获得计算长方形的面积函数
result = getAreaByFunc(::rectangleArea, 10.0, 15.0)
println("宽10 高15的长方形面积为: $result")
}
No matter what method is used, it is the use of the function type, (Double, Double) → Double
, there is nothing difficult, and it is the same as other types of usage.