首页 > 解决方案 > 从 Kotlin 的映射中过滤空键和值

问题描述

我有一个扩展功能,可以过滤掉带有空键或值的条目:

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.

有没有办法让我的扩展功能适用于这两种情况,还是我需要提供两个单独的功能?

标签: genericskotlinextension-function

解决方案


我稍后会弄清楚原因,但添加到地图中是有效的:

fun <K : Any, V : Any> Map<out K?, V?>.filterNotNull(): Map<K, V> = ...

推荐阅读