5

I use a lambda to handle callbacks from an asynchronous call. I'd like to define the callback outside the calling method to avoid a bulky method, but I can't seem to use early returns within the lambda, which makes the code unnecessarily difficult to read.

I've tried defining the lambda as a variable but returns are not viable inside the lambda.

I've tried defining the lambda inside a function and returning but returns were not viable there either.

For example:

 private fun onDataUpdated(): (Resource<List<Int>>) -> Unit =  {
   if (it.data.isNullOrEmpty()) {          
     // Handle no data callback and return early.
     return@onDataUpdated // This is not allowed   
    }

   // Handle the data update
   }
 }

I've also tried:

 private val onDataUpdated: (Resource<List<Int>>) -> Unit =  {
   if (it.data.isNullOrEmpty()) {          
     // Handle no data callback and return early.
     return // This is not allowed   
    }

   // Handle the data update
   }
 }

I'd like to perform an early return instead of using an else case, to avoid unnecessary indent, but I can't seem to find a way to use returns inside a lambda.

1
  • See my answer here: stackoverflow.com/a/74740489/9585130 Commented Dec 9, 2022 at 8:24

2 Answers 2

10

You can achieve this by labelling the lambda. For example, if you label it with dataUpdated:

private val onDataUpdated: (Resource<List<Int>>) -> Unit = dataUpdated@ {
    if (it.data.isNullOrEmpty()) {
        // Handle no data callback and return early.
        return@dataUpdated
    }

    // Handle the data update
}
Sign up to request clarification or add additional context in comments.

Comments

1

Usually you'll just put the "return" at the bottom of the lambda. Here's an example using Dispatchers.IO:

var res = async(Dispatchers.IO){
   var text : String? = null
   if(channel==null) {
      text = networkRequest(url)
   }
   text
}.await()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.