[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.3 Using a function as the return value of another function
A function can be used as the return value of another function, then this function is a higher-order function. The return type of the calculate function we wrote before is (Int,Int)->Int function type,
This shows that calculate is a higher-order function.
Here's another example of using a function as the return value of another function:
// 定义计算长方形面积的函数
// 函数类型(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
fun getArea(type: String): (Double, Double) -> Double {
var returnFunction: (Double, Double) -> Double
when (type) {
"rect" -> returnFunction = ::rectangleArea
else -> returnFunction = ::triangleArea
}
return returnFunction
}
fun main() {
// 获取计算三角形面积函数
var area: (Double, Double) -> Double = getArea("tria")
println("底10 高15的三角形面积为: ${
area(10.0, 15.0)}")
// 获取计算长方形面积函数
area = getArea("rect")
println("宽10 高15的长方形面积: ${
area(10.0, 15.0)}")
}
The above code fun getArea
defines the function getArea, and its return type is (Double, Double)->Double, which means that the return value is a function type.
var returnFunction: (Double, Double) -> Double
The code declares the returnFunction variable, explicitly specifying that its type is
(Double, Double)->Double function type.