[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.3 Lambda expressions
Lambda expressions are anonymous functions that can be used as expressions, function parameters, and function return values. The operation result of a Lambda expression is a function.
13.3.2 Using Lambda Expressions
Lambda expressions are also function types, which can declare variables, and can also be used as parameters or return values of other functions.
We've written this example before as a return value:
The following describes an example of using a Lambda expression as a parameter. The sample code is as follows:
// 打印计算结果函数
fun calculatePrint(n1: Int, n2: Int, opr: Char, funN: (Int, Int) -> Int) {
println("$n1 $opr $n2 = ${
funN(n1, n2)}")
}
fun main() {
calculatePrint(10, 5, '+', {
a: Int, b: Int -> a + b })
calculatePrint(10, 5, '-', funN = {
a: Int, b: Int -> a - b })
}
nothing wrong.