Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do Kotlin Lambda functions not execute when called?

Tags:

kotlin

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?

like image 988
Zorgan Avatar asked Feb 28 '19 08:02

Zorgan


People also ask

How do you pass lambda as parameter Kotlin?

In Kotlin, a function which can accept a function as parameter or can return a function is called Higher-Order function. Instead of Integer, String or Array as a parameter to function, we will pass anonymous function or lambdas. Frequently, lambdas are passed as parameter in Kotlin functions for the convenience.

Can you call function in lambda?

We can declare a lambda function and call it as an anonymous function, without assigning it to a variable.

How do I return from lambda Kotlin?

Just use the qualified return syntax: return@fetchUpcomingTrips . In Kotlin, return inside a lambda means return from the innermost nesting fun (ignoring lambdas), and it is not allowed in lambdas that are not inlined. The return@label syntax is used to specify the scope to return from.


1 Answers

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

like image 68
Fred Avatar answered Sep 18 '22 12:09

Fred