Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

314
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda