Home > Software engineering >  Kotlin - lambda argument outside parenthesis
Kotlin - lambda argument outside parenthesis

Time:02-18

having following function

fun functionOne(element: Int, func1: (index: Int) -> Unit) {
    println("element=$element")
    func1(element)
}

I can call it that way:

functionOne(element = 123, func1 = {index -> println("index: $index")})

no compilator complains

functionOne(123,  {index -> println("index: $index")})

now compilator suggests Lambda argument should be moved out of parentheses

or

functionOne(123) { index -> println("index: $index") }

no complains

however, unless I don't get it right, this begavior is limited to exactly one lambda argument, that is having

fun functionTwo(element: Int, func1: (index: Int) -> Unit, func2: (index: Int) -> Unit) {
    println("element=$element")
    func1(element)
    func2(element)
}

I can make a call like this

functionTwo(123, { index -> println("index: $index")},  { index -> println("index2: $index")})

but this one does not compile

functionTwo(456) {index -> println("index: $index"} { index -> println("index2: $index")})

can you please confirm that or let me know to move lambda arguments out of parentheses

thanks!

CodePudding user response:

According to the documentation, only trailing lambdas can be placed outside the parenthesis:

Passing trailing lambdas

According to Kotlin convention, if the last parameter of a function is a function, then a lambda expression passed as the corresponding argument can be placed outside the parentheses:

val product = items.fold(1) { acc, e -> acc * e }

Such syntax is also known as trailing lambda.

If the lambda is the only argument in that call, the parentheses can be omitted entirely:

run { println("...") }

This implies that you can not move the second-to-last lambda expression outside of the parenthesis, and thus that you cannot move multiple lambda expressions out of the parenthesis.

  • Related