In the following code I have 2 functions - first one wrapped in a lambda body and the other without.
fun first() = { println("first")}
fun second() = println("second")
first()
second()
Only second()
prints - why is this?
In Kotlin, a function which can accept a function as parameter or can return a function is called Higher-Order function. Instead of Integer, String or Array as a parameter to function, we will pass anonymous function or lambdas. Frequently, lambdas are passed as parameter in Kotlin functions for the convenience.
We can declare a lambda function and call it as an anonymous function, without assigning it to a variable.
Just use the qualified return syntax: return@fetchUpcomingTrips . In Kotlin, return inside a lambda means return from the innermost nesting fun (ignoring lambdas), and it is not allowed in lambdas that are not inlined. The return@label syntax is used to specify the scope to return from.
The first one is a function that returns a function. What happens in fact is that first()
returns another function that prints "first", but doesn't execute it.
To do this you have to call it by adding another set of of parenthesis:
first()()
// Or
val resultOfFirst = first()
resultOfFirst()
This happens because the =
sign for functions is analogous to a return statement and when you wrap things in {}
you're in fact creating a lambda. Hence, first returns a lambda, but doesn't execute it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With