IN line return@withContext cachedCategories because it can't just be return cachedCategories only. Whats @withContext ?
Code full:
@Singleton class FoodMenuRemoteSource @Inject constructor(private val foodMenuApi: FoodMenuApi) {
private var cachedCategories: List<FoodItem>? = null
suspend fun getFoodCategories(): List<FoodItem> = withContext(Dispatchers.IO) {
var cachedCategories = cachedCategories
if (cachedCategories == null) {
cachedCategories = foodMenuApi.getFoodCategories().mapCategoriesToItems()
[email protected] = cachedCategories
}
return@withContext cachedCategories
}
You are not allowed to have a non-local return in a lambda. That's why @withContext is necessary. You see, the code block there is in fact not the body of the
getFoodCategoriesbut the lambda function that is the second argument ofwithContext. Also, the last expression in a lambda is automatically also the return value of it, so you can actually leave thereturn@withContextout completely like this