7

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?

4 Answers 4

9

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

Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

2

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

Comments

0

Try

first()()

or

first().invoke()

first returns a function, it does not invoke it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.