简体   繁体   English

对于Kotlin中的高阶函数,为什么lambda显示在其他函数参数之外?

[英]With higher-order functions in Kotlin, why are lambdas shown outside of other function parameters?

In some training I'm reviewing, I don't understand exactly how an example higher-order function and lambda are connected through syntax 在我正在审查的一些培训中,我不完全了解示例高阶函数和lambda是如何通过语法连接的

This higher-order Kotlin function 此高阶Kotlin函数

fun myWith(name: String, block: String.() -> Unit) {
  name.block()
}

Is invoked like this 像这样被调用

myWith(fish.name) {
  capitalize()
}

I understand the second part is a lambda but I don't understand why it's not included as a second parameter to the function and just hung outside of the parameters. 我知道第二部分是lambda,但我不明白为什么它不作为函数的第二个参数不包括在内而只是挂在参数之外。 Like why is it not invoked as: 就像为什么不将其调用为:

myWith(fish.name, { capitalize() } )

Later a more verbose description of the example is shown as 稍后,该示例的详细说明如下所示:

myWith(fish.name, object : Function1<String, Unit> {
  override fun invoke(name: String) {
    name.capitalize()
  }
})

Which IS including the lambda inside the normal list of parameters to myWith 哪个IS包含lambda到myWith的常规参数列表中

In Kotlin, there is a convention that if the last parameter of a function accepts a function, a lambda expression that is passed as the corresponding argument can be placed outside the parentheses. 在Kotlin中,有一个约定,如果函数的最后一个参数接受函数,则可以将作为相应参数传递的lambda表达式放在括号之外。

Source: https://kotlinlang.org/docs/reference/lambdas.html#passing-a-lambda-to-the-last-parameter 资料来源: https : //kotlinlang.org/docs/reference/lambdas.html#passing-a-lambda-to-the-last-parameter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM