我有一个扩展功能,可以过滤掉带有空键或值的条目:
fun <K, V> Map<K?, V?>.filterNotNull(): Map<K, V> = this.mapNotNull {
it.key?.let { key ->
it.value?.let { value ->
key to value
}
}
}.toMap()
这适用于具有可为空键和值的映射:
data class Stuff(val foo: Int)
val nullMap = mapOf<String?, Stuff?>(null to (Stuff(1)), "b" to null, "c" to Stuff(3))
assert(nullMap.filterNotNull().map { it.value.foo } == listOf(3))
但不是在具有不可为空的键或值的情况下:
val nullValues = mapOf<String, Stuff?>("a" to null, "b" to Stuff(3))
assert(nullValues.filterNotNull().map { it.value.foo } == listOf(3))
Type mismatch: inferred type is Map<String, Stuff?> but Map<String?, Stuff?> was expected
Type inference failed. Please try to specify type arguments explicitly.
有没有办法让我的扩展功能适用于这两种情况,还是我需要提供两个单独的功能?