Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

311
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda