basically: ``` val list: List<Pair<String, ...
# announcements
b
basically:
Copy code
val list: List<Pair<String, String>> = listOf(
            "a" to null,
            "b" to "hi"
        )
            .filter {it.second != null}
a
Not sure if mapNotNull works?
listOf("a" to "b", "c" to null).mapNotNull { if(it.second == null) null else it }
Maybe you would need a
it as Pair<String, String>
but idk
l
if (it.second == null) null else it
is useless, just use
.mapNotNull { it.second }
🤔 1
b
right, I need it.first as well though
l
@Alowaniak the check is doing exactly this 🙂
a
.mapNotNull { it.second }
would map to the second element, he would indeed lose the
it.first
b
@Alowaniak your example just asserts that the pair is not null
it still returns a Pair<String, String?>
a
even when adding
as Pair<String, String>
?
b
nah, but I suppose I can just cast it anyways
shouldn’t be any different than using !! in that case
which basically just circumvents the typechecker to error at runtime
which itself is fine if your function is generic enough that you have to review it only once
a
Well you could make a function of it and then do:
Copy code
fun nonNullPair(from: Pair<String, String?>): Pair<String, String>? {
    return from.first to (from.second ?: return null)
}

fun main() {
    val xs: List<Pair<String, String>> = listOf("a" to "b", "c" to null).mapNotNull(::nonNullPair)
    println(xs)
}
k
Does anyone know a language where stuff like this works? What does the type system have to look like? I know the Kotlin team is thinking about this (https://github.com/Kotlin/KEEP/blob/master/proposals/kotlin-contracts.md#open-questions), but I'm curious if there's a precedent.
a
Typescript supports it when the method for filter used has a typeguard, which I think are sort of similar to contracts?