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.
The lambda functions do not need a return statement, they always return a single expression.
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.
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 .
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With