Why does this not compile?

fun <K, V> Array<Pair<K, V?>>.filterNotNullBySecond(): List<Pair<K, V>> {
    val destination = ArrayList<Pair<K, V>>()
    for (element in this) {
        val second = element.second
        if (second != null) destination.add(Pair(element.first, second))
    }
    return destination
}

fun <K, V> mapOfNonNullValues(vararg pairs: Pair<K, V?>): Map<K, V> =
    mapOf(*pairs.filterNotNullBySecond().toTypedArray())

I get an error on compiling:

Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: public fun <K, V> Array<Pair<TypeVariable(K), TypeVariable(V)?>>.filterNotNullBySecond(): List<Pair<TypeVariable(K), TypeVariable(V)>> defined in root package in file File.kt

This is because filterNotNullBySecond() may potentially modify the contents of the array and pairs should not be modified. Even if in fact filterNotNullBySecond() does not modify it, we need to inform the compiler about that by specifying the variance:

fun <K, V> Array<out Pair<K, V?>>.filterNotNullBySecond()
1 Like

Oh okay… thanks for the answer…