Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using return inside a lambda?

Tags:

lambda

kotlin

In the code below, I want to show my empty views if trips is empty and then return and avoid running the below code, but the compiler says "return is not allowed here".

mainRepo.fetchUpcomingTrips { trips ->     if (trips.isEmpty()) {         showEmptyViews()         return     }      // run some code if it's not empty } 

Is there a way to return like that?

I know I can just put it in an if else block but I hate writing if else's, it's less understandable/readable in my opinion when there's a few more conditions.

like image 288
JozeRi Avatar asked Jul 27 '17 10:07

JozeRi


People also ask

Can we use return in lambda?

The lambda functions do not need a return statement, they always return a single expression.

What is return type in lambda?

The return type for a lambda is specified using a C++ feature named 'trailing return type'. This specification is optional. Without the trailing return type, the return type of the underlying function is effectively 'auto', and it is deduced from the type of the expressions in the body's return statements.

Can lambda return string?

A free variable can be a constant or a variable defined in the enclosing scope of the function. The lambda function assigned to full_name takes two arguments and returns a string interpolating the two parameters first and last .

Is return keyword is not allowed inside the lambda expression?

Java Lambda Expression Example: with or without return keyword. In Java lambda expression, if there is only one statement, you may or may not use return keyword. You must use return keyword when lambda expression contains multiple statements.


1 Answers

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. You can use the name of the function the lambda is passed to (fetchUpcomingTrips) as the label:

mainRepo.fetchUpcomingTrips { trips ->     if (trips.isEmpty()) {         showEmptyViews()         return@fetchUpcomingTrips      }      // ... } 

Related:

  • Return at labels in the language reference

  • Whats does “return@” mean?

like image 157
hotkey Avatar answered Oct 01 '22 05:10

hotkey