从Kotlin的地图中过滤空键和值

neu*_*242 2 generics kotlin extension-function

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

fun <K, V> Map<K?, V?>.filterNotNull(): Map<K, V> = this.mapNotNull { 
   it.key?.let { key -> 
      it.value?.let { value -> 
         key to value 
      }
   }
}.toMap()
Run Code Online (Sandbox Code Playgroud)

这适用于具有可空键和值的地图:

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))
Run Code Online (Sandbox Code Playgroud)

但不能包含非空键或值的值:

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.
Run Code Online (Sandbox Code Playgroud)

有没有办法使我的扩展功能在两种情况下都起作用,还是需要提供两个单独的功能?

tie*_*edh 5

我稍后会找出原因,但将其添加到地图中是可行的:

fun <K : Any, V : Any> Map<out K?, V?>.filterNotNull(): Map<K, V> = ...
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!看起来`out`关键字就是我所需要的,不需要`:Any`。 (2认同)