当前位置:网站首页>Higher order functions in kotlin (first-class citizens)

Higher order functions in kotlin (first-class citizens)

2022-06-21 08:14:00 Dialogue

So let's talk about that Kotlin Higher order functions in

Kotlin Not a pure object-oriented language , Kotlin The function of is also a first-class citizen , So the function itself has its own The type of . Function types are like the data types described above , It can be used to define variables , It can also be used as a formal parameter class of a function type , It can also be used as the return value type of the function

  • Use function types

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

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

List of formal parameters of the function 、-> And return value types are (Int , String) -> String, This is the type of the function .

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

List of formal parameters of the function 、 .> And return value types are (Double , Double)-> Unit or (Double, Double), This is Is the type of the function .

fun test() {
	....
}

List of formal parameters of the function 、 ·> And return value types are () ->Unit or (), This is the type of the function .

for example :
// Define a variable , The type of ( Int, Int) - > Int
var myfun : (Int , Int) -> Int
// Define a variable disk , The type of ( Stri mouth  g)
var test : (String)

After defining variables of function type , You can assign a function to this 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
// take  pow  The function is assigned to  my fun , be  my fun  It can be taken as  pow  Use 
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
// take  area  The function is assigned to  my fun , be  myfun  It can be taken as  area  Use 
myfun = : : area
println(myfun(3,4))// Output  12

In turn pow()、 area() The function is assigned to myfun Variable ——— As long as it is assigned Function type and myfun The variable types of are consistent , You can assign the value successfully .

When accessing a function reference directly , Instead of calling a function , You need to add two colons before the function name , and And you can't add parentheses after a function Once you add parentheses , It becomes a call function , Instead of accessing function references . By using variables of function type , It can make myfun Point to different functions at different times , So that the program is more More flexibility . thus it can be seen , The advantage of using function types is to make the program more flexible . besides , Programs can also use function types as parameter types and return value types .

  • Use function type as parameter type

Kotiin Support the use of function types as other types , Therefore, the shape of function type can be defined in the function ginseng

Example
// Define the formal parameters of the function type , among  fn  yes ( Int )→ Int  Type parameters 
fun map (data : Array<Int>, fn: (Int) -> Int) : Array<Int> {
    var result = Array<Int>(data.size, { 0 })
// Traverse  data  Each element of the array , And use  fn  Function pair  data[i ] Calculate 
// Then take the result of the calculation 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 factorials 
            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(" The original data ${data.contentToString()}")
                    // The following program code calls  map () function  3  Time  ,  Each call passes in a different function 
                    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(" Calculate the factorial of array elements ")
                    println(map(data,::factorial).contentToString())

                    }

Defined a map() function , The second parameter of the function is a formal parameter of a function type , This means This means that each time a function is called, a function can be dynamically passed in , As the actual incoming function changes , Can change dynamically map() Part of the calculation code in the function .

map() function 3 Time , 3 The following calls are passed in sequence square、 cub e 、 fac toria l Function as parameter , So every time I call map() The actual execution code of the function is different

  • Use the function type as the return value type

Kotlin It also supports defining the return value of function types , In this way, other functions can be used as the return value of the function

Example
// Defined function , The return value type of this function 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 (), The program returns a ( Int )→ Int  Function of type 
    var mathFunc = getMathFunc("cube")// obtain  cube  function 
    println(mathFunc(5)) // Output  125
    mathFunc = getMathFunc("square") // obtain j square  function 
    println(mathFunc(5)) // Output  25
    mathFunc = getMathFunc("other")// obtain  factorial  function 
    println(mathFunc(5)) // Output  120
}
原网站

版权声明
本文为[Dialogue]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202221502095542.html