Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

317
Views
Why do Kotlin Lambda functions not execute when called?

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?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report

0

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

over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!