Higher order function in Kotlin (first class citizen)

Let's talk about higher-order functions in Kotlin

Kotlin is not a pure object-oriented language. Kotlin's function is also a first-class citizen, so the function itself has its own type. Like the data types described earlier, function types can be used to define variables, function parameter types, and return value types of functions

  • Use function type

Each function of Kotlin has a specific type. The function type is composed of the formal parameter list, · > and return value type of the function. For example, the following functions:

fun foo(a : Int , name:String) ->String{
		....
}

The formal parameter list, - > and return value types of the function are (int, string) - > string, which is the type of the function.

fun bar(width : Double , height: Double) {
		....
}

The formal parameter list,. And return value types of the function are (Double, Double) - > unit or (Double, Double), which is the type of the function.

fun test() {
	....
}

The formal parameter list, · > and return value types of the function are () - > Unit or (), which is the type of the function.

For example:
//Define a variable whose type is (int, int) - > int
var myfun : (Int , Int) -> Int
//Define a variable disk whose type is (Stri port g)
var test : (String)

After defining a variable of function type, you can assign a function to the variable.

//Define a function that calculates the power
fun pow (ba$e: Int , exponent: Int) : Int {
var result = 1
for ( i in 1 . . exponent) {
result *= base
return result
//Assign the pow function to my fun, then my fun can be used as pow
myfun = ::pow
println(myfun(3 , 4)) //Output 81
//Define a function to calculate the area
fun area(width: Int , height : Int) : Int {
return width * height
//Assign the area function to my fun, then myfun can be used as area
myfun = : : area
println(myfun(3,4))//Output 12

Assign the pow() and area() functions to the myfun variable in turn -- as long as the assigned function type is consistent with the variable type of myfun, the assignment can be successful.

When you directly access the function reference of a function instead of calling the function, you need to add two colons in front of the function name, and you can't add parentheses after the function -- once you add parentheses, it becomes a calling function instead of accessing the function reference. By using function type variables, you can make myfun point to different functions at different times, which makes the program more flexible. Thus, the advantage of using function types is to make the program more flexible. In addition, programs can also use function types as parameter types and return value types.

  • Use function type as parameter type

Kotiin supports the use of function types like other types, so it is entirely possible to define formal parameters of function types in functions

example
//Define the formal parameter of function type, where fn is the formal parameter of type (Int) → Int
fun map (data : Array<Int>, fn: (Int) -> Int) : Array<Int> {
    var result = Array<Int>(data.size, { 0 })
//Traverse each element of the data array and calculate data[i] with fn function
//Then take the calculation result as the element of the new array
    for (i in data.indices) {
        result[i] = fn(data[i])
    }
    return result
}
    //Define a function that calculates the square
    fun square (n : Int) : Int {
        return n *n
        //Define a function that calculates the cube
        fun cube(n : Int) : Int {
            return n * n * n
        }
            //Define a function that calculates factorial
            fun factorial (n: Int ) : Int {
                var result = 1
                for (index  in 2 .. n) {
            result *= index
            return result
        }
                fun main(args : Array<String>) {
                    var data= arrayOf (3 , 4 , 9 , 5 , 8)
                    println("Original data ${data.contentToString()}")
                    //The following program code calls the map () function three times, and different functions are passed in each time
                    println("Calculate the square of array elements")
                    println(map(data,::square).contentToString())
                    println("Calculates the cube of an array element")
                    println(map((data,::cube).contentToString())
                    println("Calculates the factorial of an array element")
                    println(map(data,::factorial).contentToString())

                    }

A map() function is defined. The second parameter of the function is a formal parameter of a function type, which means that a function can be dynamically passed in every time the function is called. With the change of the actual incoming function, part of the calculation code in the map() function can be dynamically changed.

The map () function is called three times, and the square, cub e and factory l functions are passed in as parameters in turn during the three calls, so that the actual execution code is different each time the map () function is called

  • Use function type as return value type

Kotlin also supports defining the return value of function types, so that other functions can be used as the return value of functions

example
//Defines a function whose return value type is l'l (Int) • Int
fun getMathFunc(type: String): (Int) -> Int {
    //Define a local function that calculates the square
    fun square(n: Int): Int {
        return n * n
    }

    //Define a local function that calculates the cube
    fun cude(n: Int): Int {
        return n * n * n
    }

    //Define a local function that calculates factorial
    fun factorial(n: Int): Int {
        var result = 1
        for (index in 2..n) {
            result *= index

        }
        return result
    }
    when (type) {
        //Return local function
        "square" -> return ::square
        "cube" -> return ::cude
        else -> return ::factorial
    }

}

fun main(args: Array<String>) {
    //Call getMathFunc(), and the program returns a function of type (Int) → Int
    var mathFunc = getMathFunc("cube")//Get cube function
    println(mathFunc(5)) //Output 125
    mathFunc = getMathFunc("square") //Get j square function
    println(mathFunc(5)) //Output 25
    mathFunc = getMathFunc("other")//Get the factorial function
    println(mathFunc(5)) //Output 120
}

Added by itreP on Tue, 22 Feb 2022 08:49:59 +0200