Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter Kotlin collection of pairs so pair content is not null

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?)

like image 620
m.reiter Avatar asked Oct 30 '25 15:10

m.reiter


1 Answers

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
    }
like image 97
Konstantin Raspopov Avatar answered Nov 01 '25 06:11

Konstantin Raspopov