Reputation: 89
In some training I'm reviewing, I don't understand exactly how an example higher-order function and lambda are connected through syntax
This higher-order Kotlin function
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. 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
Upvotes: 1
Views: 660
Reputation: 841
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.
Source: https://kotlinlang.org/docs/reference/lambdas.html#passing-a-lambda-to-the-last-parameter
Upvotes: 3