GenerationTech
GenerationTech

Reputation: 89

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

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

Answers (1)

Diego Magdaleno
Diego Magdaleno

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

Related Questions