2017-07-27 37 views
5

在下面的代碼中,我想顯示我的空視圖,如果旅行是空的,然後返回並避免運行下面的代碼,但編譯器說「返回不允許在這裏」。在lambda中使用return?

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

    // run some code if it's not empty 
} 

有沒有辦法像那樣返回?

我知道我可以把它放在一個if else塊中,但是我討厭寫作,如果有其他東西,在我看來只有更多的條件時,這是不太可理解/可讀的。

回答

14

只需使用限定的返回語法:[email protected]

在Kotlin中,return裏面的lambda表示從最內層嵌套fun(忽略lambda表示)返回,並且不允許在不是inlined的lambdas中。

[email protected]語法用於指定要從中返回的範圍。您可以使用拉姆達傳遞給(fetchUpcomingTrips)功能作爲標籤的名稱:

mainRepo.fetchUpcomingTrips { trips -> 
    if (trips.isEmpty()) { 
     showEmptyViews() 
     [email protected] 
    } 

    // ... 
} 

相關:

3

Plain return表示你從函數返回。既然你不能從lambda函數中返回,編譯器會抱怨。相反,你想從拉姆達回來,你必須使用一個標籤:

mainRepo.fetchUpcomingTrips { trips -> 
      if (trips.isEmpty()) { 
       showEmptyViews() 
       [email protected] 
      } 

      //run some code if it's not empty 
     } 
1

的回報讓我們從外部函數返回。最重要的用例是從lambda表達式返回

匿名函數中的返回語句將從匿名函數本身返回。

fun foo() { 
ints.forEach(fun(value: Int) { 
    if (value == 0) return // local return to the caller of the anonymous fun, i.e. the forEach loop 
    print(value) 
}) 
} 

當返回一個值,該解析器優先選擇合格的返回,即

[email protected] 1 

是指「在標籤@a返回1」而不是「返回一個標記的表達(@a 1) 」。 返回默認情況下從最近的封閉函數或匿名函數返回。

中斷終止最近的封閉循環。

繼續進行到最近的封閉循環的下一步。

更多詳情,請參閱Returns and Jumps,Break and Continue Labels

0

return另一種可能是

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