过滤 Kotlin 的对集合,使对内容不为空

m.r*_*ter 4 collections nullable kotlin

我正在寻找一种将 a 过滤List<Pair<T?, U?>>为 a 的方法List<Pair<T, U>>:我想忽略包含 null 的对。

有效,但我也需要智能广播:

fun <T, U> List<Pair<T?, U?>>.filterAnyNulls() = 
    filter { it.first != null && it.second != null }
Run Code Online (Sandbox Code Playgroud)

可以用,但是很难看!!,而且一点也不符合习惯

fun <T, U> List<Pair<T?, U?>>.filterAnyNulls() = mapNotNull {
    if (it.first == null || it.second == null) {
        null
    } else {
        Pair(it.first!!, it.second!!)
    }
}
Run Code Online (Sandbox Code Playgroud)

有什么好的解决方案吗?还有更通用的解决方案吗?(甚至可能在可以解构的类中,例如三元组或数据类?)

小智 5

该解决方案利用解构和智能强制转换,并且可以满足您的需要,而且不会丑陋!!

fun <T, U> List<Pair<T?, U?>>.filterPairs(): List<Pair<T, U>> =
    mapNotNull { (t, u) ->
        if (t == null || u == null) null else t to u
    }
Run Code Online (Sandbox Code Playgroud)