2016-07-22 5 views
12

問題

Kotlin型システムにおけるヌル・安全のこの制限を回避作業の慣用的な方法は何ですか?Kotlin:リスト(または他の機能の変換)からヌルを排除

val strs1:List<String?> = listOf("hello", null, "world") 

// ERROR: Type Inference Failed: Expected Type Mismatch: 
// required: List<String> 
// round: List<String?> 
val strs2:List<String> = strs1.filter { it != null } 

この質問はちょうどヌルを排除についてではないですが、また、型システムを作るためには、ヌルが変換によってコレクションから削除されていることを認識しています。

私はループしない方がいいですが、そうするのが最善の方法だと思います。

ワークアラウンド

以下のコンパイルが、私はそれはそれを行うための最善の方法だか分からない:

fun <T> notNullList(list: List<T?>):List<T> { 
    val accumulator:MutableList<T> = mutableListOf() 
    for (element in list) { 
     if (element != null) { 
      accumulator.add(element) 
     } 
    } 
    return accumulator 
} 
val strs2:List<String> = notNullList(strs1) 

答えて

20

あなたがここにfilterNotNull

を使用することができますが、簡単な例です。

でも、stdlibはあなたが書いたのと同じことをします

/** 
* Appends all elements that are not `null` to the given [destination]. 
*/ 
public fun <C : MutableCollection<in T>, T : Any> Iterable<T?>.filterNotNullTo(destination: C): C { 
    for (element in this) if (element != null) destination.add(element) 
    return destination 
} 
+2

Sweet!ドー!なぜ私はそれを見ませんでしたか? :-) – GlenPeterson

+1

リストを作成している場合は 'listOfNotNull'も使用できます – Mijail

関連する問題