I am looking for a way to filter a List<Pair<T?, U?>> to a List<Pair<T, U>>: I would like to ignore pairs containing null.
Works, but i need smartcasting, too:
fun <T, U> List<Pair<T?, U?>>.filterAnyNulls() = 
    filter { it.first != null && it.second != null }
Works, but ugly !!, and does not feel idiomatic at all
fun <T, U> List<Pair<T?, U?>>.filterAnyNulls() = mapNotNull {
    if (it.first == null || it.second == null) {
        null
    } else {
        Pair(it.first!!, it.second!!)
    }
}
Any nice solutions? And any more generic solutions? (Maybe even in classes which can be deconstructed, like triples or data classes?)
This solution utilizes destructuring and smart casts and will do what you need without ugly !!:
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
    }
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With