Reputation: 9173
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?
Upvotes: 7
Views: 3887
Reputation: 4773
It's very simple. Check types of those:
fun first(): () -> Unit = { println("first") }
fun second(): Unit = println("second")
So, when you call first
you get lamda expression. To invoke this function use .invoke()
(or simply ()
):
first().invoke()
// or
first()()
Second is obvious - it's executed on call.
Upvotes: 5
Reputation: 29209
Try
first()()
or
first().invoke()
first
returns a function, it does not invoke it.
Upvotes: 0
Reputation: 17095
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
Upvotes: 9
Reputation: 21829
The function first
returns a function { println("first")}
.
Calling first()
does nothing - not even its return argument is catched.
Without a lambda an equivalent would be, maybe it is easier to understand it in this form:
fun firstWithoutLambda() = fun() { println("first w/o lambda")}
To call them:
first().invoke()
firstWithoutLambda().invoke()
which will print the messages that you would expect.
From the original Kotlin tutorial a good article: https://kotlinlang.org/docs/reference/lambdas.html
Upvotes: 2