2017-09-04 127 views
1

我正在尋找一種慣用的方式來返回Kotlin中的變量(如果不爲null)。例如,我想的東西,如:在Kotlin中如果不爲空,返回的語法方式

for (item in list) { 
    getNullableValue(item).? let { 
    return it 
    } 
} 

但它不可能在科特林一個let塊內返回。

有沒有做到這一點,而不必做一個好辦法:

for (item in list) { 
    val nullableValue = getNullableValue(item) 
    if (nullableValue != null) { 
    return nullableValue 
    } 
} 
+1

可以從'let {}'返回''。你的兩個片段都是正確的,並且完全一樣。 – voddan

回答

3

不知道這是否會被稱爲地道,但你可以做到這一點:

val nullableValue = list.find { it != null } 
if (nullableValue != null) { 
    return nullableValue 
} 

編輯:

根據s1m0nw1的回答,你可以減少到這個:

list.find { it != null }?.let { 
    return it 
} 
+1

對我來說看起來相當習慣。可能甚至不需要_if_:'return list.find {it!= null}'似乎可以解決問題。 –

3

,能夠從let返回,因爲你可以在documentation讀:

返回表達從最近的封閉功能,即FOO返回。 (請注意,這種非本地回報率只爲傳遞給內聯函數lambda表達式的支持。)

let()inline功能,因此您自動封閉功能,在此返回時,你做returnlet,像例如:

fun foo() { 
    ints.forEach { 
     if (it == 0) return // nonlocal return from inside lambda directly to the caller of foo() 
     print(it) 
    } 
} 

要修改行爲 「標籤」 可用於:

fun foo() { 
    ints.forEach [email protected] { 
     if (it == 0) [email protected] 
     print(it) 
    } 
} 
0

這樣做的「正確」慣用方式是使用「第一個」方法。

實施例:

val x = listOf<Int?>(null, null, 3, null, 8).first { it != null }

他的具體例子將是

return list.first {getNullableValue(it) != null}

相關問題