高阶函数很复杂?

Fur*_*kan 0 lambda higher-order-functions kotlin

我已经阅读了很多文章,但仍有一些我难以理解的事情。我不明白的地方在哪里?我的问题在代码中。我希望我问对了。

fun main() {
    /*
    1- Is it argument or parameter in numbers{} block?
    where is it sent to the argument? why do we send "4" if it is parameter?
    Are all the functions I will write in (eg println) sent to the numbers function? But this HOF can 
    only take one parameter.
    */
    numbers {
        /*
        2-How does this know that he will work 3 times?
        According to the following 3 functions? Is there a for loop logic??
        */
        println(it)
        "4" // 3- Which one does this represent? f:(String) or ->String?
    }
}

fun numbers(f: (String) -> String) {
    f("one")
    f("two")
    f("three")
    println(f(" - "))
}
Run Code Online (Sandbox Code Playgroud)

Ten*_*r04 9

  1. 上面的 lambda 块中没有定义参数或参数。这只是 lambda 函数的内容。您已经使用了 it. "4"是你的 lambda 的返回值。
  2. lambda 本身并不“知道”它将被调用多少次。在这种情况下,它被调用了四次,因为您的 numbers 函数调用了该参数f四次。
  3. lambda 的返回值是其最后一个表达式的计算结果。在这种情况下,它返回String "4".

也许这会有所帮助。Lambda 语法很方便。但是我们可以一次拿走每块语法糖,看看它的实际含义。

下面的所有代码块都具有完全相同的含义。

这是你的原始声明:

numbers { 
    println(it)
    "4"
}
Run Code Online (Sandbox Code Playgroud)

首先,当 lambda 省略单个参数时,它会获得隐式参数 name it。如果我们避免使用这种糖,它看起来像这样:

numbers { inputString ->
    println(inputString)
    "4"
}
Run Code Online (Sandbox Code Playgroud)

lambda 中最后一个表达式的计算值就是它返回的值。你也可以显式地写一个 return 语句,但你必须指定你是从 lambda 返回的,所以你必须输入它的名字。所以如果我们把它放进去,它看起来像这样:

numbers { inputString ->
    println(inputString)
    return@numbers "4"
}
Run Code Online (Sandbox Code Playgroud)

当 lambda 是您传递给函数的最后一个参数时,您可以将它放在括号之外。这称为“尾随 lambda”。如果函数是唯一的参数,则根本不需要括号。如果我们跳过这个方便,它看起来像这样:

numbers({ inputString ->
    println(inputString)
    return@numbers "4"
})
Run Code Online (Sandbox Code Playgroud)

lambda 只是定义函数的一种非常紧凑的方式。如果我们直接定义函数,它看起来是这样的:

numbers(fun(inputString: String): String {
    println(inputString)
    return "4"
})
Run Code Online (Sandbox Code Playgroud)

您传递的函数是函数的参数numbers()。您也可以单独定义它,然后像这样传递函数引用:

fun myFunction(inputString: String): String {
    println(inputString)
    return "4"
}
numbers(::myFunction)
Run Code Online (Sandbox Code Playgroud)