https://kotlinlang.org logo
#announcements
Title
# announcements
p

pavel

10/31/2019, 9:29 PM
I have a
List<Pair<A,B?>>
Is there an easy way to filter out all where
second==null
and make the type be
List<Pair<A,B>>
?
k

karelpeeters

10/31/2019, 9:35 PM
Not, you'll have to cast it.
b

bezrukov

10/31/2019, 9:35 PM
You can try mapNotNull - convert
Pair<A,B?>
To
Pair<A,B>?
k

karelpeeters

10/31/2019, 9:35 PM
How to express this is still an open question for contracts: https://github.com/Kotlin/KEEP/blob/master/proposals/kotlin-contracts.md#open-questions
p

pavel

10/31/2019, 9:37 PM
Thanks
b

bezrukov

10/31/2019, 9:37 PM
Something like
list.mapNotNull{if (it.second != null) it.first to it.second else null}
p

pavel

10/31/2019, 9:41 PM
nope, that didn’t work. The inferred type is still
List<Pair<A,B?>>
k

karelpeeters

10/31/2019, 9:45 PM
You need an intermediate variable, something like
Copy code
list.mapNotNull {
    val second = it.second
    if (second == null) null else it.first to second
}
b

bezrukov

10/31/2019, 9:48 PM
list.mapNotNull { (first, second) -> second?.let { first to second } }
1
p

pavel

10/31/2019, 9:54 PM
ooo, nice
thank you
2 Views