Using return inside a lambda?

Viewed 34809

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.

6 Answers

You can also replace { trips -> with fun(trips) { to form an anonymous function which can use return normally.

You can Return to Labels:

fun foo() {
    println("begin foo")
    listOf(1, 2, 3, 4, 5).forEach lit@{
        // local return, meaning this function execution will end
        // the forEach will continue to the next element in the loop
        if (it == 3) return@lit
        
        println("- $it")
    }
    println("done with explicit label")
}

Playground demo here.

Related