https://kotlinlang.org logo
Title
b

Bernhard

09/02/2019, 2:04 PM
basically:
val list: List<Pair<String, String>> = listOf(
            "a" to null,
            "b" to "hi"
        )
            .filter {it.second != null}
a

Alowaniak

09/02/2019, 2:06 PM
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

Luca Nicoletti

09/02/2019, 2:08 PM
if (it.second == null) null else it
is useless, just use
.mapNotNull { it.second }
🤔 1
b

Bernhard

09/02/2019, 2:08 PM
right, I need it.first as well though
l

Luca Nicoletti

09/02/2019, 2:09 PM
@Alowaniak the check is doing exactly this 🙂
a

Alowaniak

09/02/2019, 2:09 PM
.mapNotNull { it.second }
would map to the second element, he would indeed lose the
it.first
b

Bernhard

09/02/2019, 2:09 PM
@Alowaniak your example just asserts that the pair is not null
it still returns a Pair<String, String?>
a

Alowaniak

09/02/2019, 2:10 PM
even when adding
as Pair<String, String>
?
b

Bernhard

09/02/2019, 2:10 PM
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

Alowaniak

09/02/2019, 2:16 PM
Well you could make a function of it and then do:
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

karelpeeters

09/02/2019, 5:10 PM
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

Alowaniak

09/03/2019, 6:34 AM
Typescript supports it when the method for filter used has a typeguard, which I think are sort of similar to contracts?