generics - 从 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.
有没有办法让我的扩展功能适用于这两种情况,还是我需要提供两个单独的功能?
解决方案
我稍后会弄清楚原因,但添加到地图中是有效的:
fun <K : Any, V : Any> Map<out K?, V?>.filterNotNull(): Map<K, V> = ...
推荐阅读
- flutter - 分组 FCM 通知颤振
- node.js - NodeJS TLS客户端连接在第一次收到请求后关闭
- php - 脚本 php 编辑价格文件 xml
- react-native - 如何在expo react native项目中获取本地视频的base64
- ansible - 在角色中使用变量到 failed_when
- python - can't running flask authentification
- c# - 将 ASP.NET Core Razor 页面中的默认页面从索引更改为主页
- php - php数组格式转换
- flutter - 颤振:位置参数太多:预期为 0,但在我将函数传递给其他函数时发现了 1
- arrays - 创建将 arrA 中的每个元素与 ArrB 中的每个元素相加的逻辑,并在它们的总和为零时输出两项的索引