[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.1 Function types
Every function in Kotlin has a type, which is called "function type". As a data type, there is no difference between the function type and the data type in usage scenarios. Variables can be declared, and can also be used as parameters of other functions or return values of other functions.
The following three function definitions are available:
// 定义计算长方形面积的函数
// 函数类型(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
// 函数类型 () → Unit
fun sayHello() {
println("Hello, world.")
}
fun main() {
val getArea: (Double, Double) -> Double = ::triangleArea
// 调用函数
val area = getArea(50.0, 40.0)
println(area)
}
In the above code, the functions rectangleArea and triangleArea. have the same function type (Double,Double) ->Double.
The function type is to keep the parameter type in the function parameter list, plus the arrow symbol and return type, the form is as follows:
参数列表中的参数类型->返回类型
Every function has a function type , even if there are no parameters in the function list, and functions that do not return a value also have a function type, such as the sayHello() function, the function type of the sayHello() function is ()->Unit.