Kotlin 如何清理地图以返回地图<;字符串,字符串>;而不是地图<;一串字符串?>;在科特林?
我有点新使用kotlin,我想知道我是否可以做这样的事情 我有一个包含Kotlin 如何清理地图以返回地图<;字符串,字符串>;而不是地图<;一串字符串?>;在科特林?,kotlin,Kotlin,我有点新使用kotlin,我想知道我是否可以做这样的事情 我有一个包含Person类型对象的列表 Person具有类似于名称、id的属性,但可以为空 所以我做了这样的东西: return persons.filter { it.name != null && it.id != null }.map { it.id to it.name }.toMap() 我个人没有看到错误,但编译器一直告诉我应该返回一个非空映射 有什么方法可以使用filter和map使
Person
类型对象的列表
Person
具有类似于名称、id的属性,但可以为空
所以我做了这样的东西:
return persons.filter {
it.name != null && it.id != null
}.map {
it.id to it.name
}.toMap()
我个人没有看到错误,但编译器一直告诉我应该返回一个非空映射
有什么方法可以使用filter和map使用lambdas函数实现吗?用于组合filter
和map
:
persons.mapNotNull {
val id = it.id
val name = it.name
if (id != null && name != null) Pair(id, name) else null
}.toMap()
将id
和name
拉入局部变量应确保它们在对(id,name)
中被推断为非空,但可能不是必需的
您的方法不起作用的原因是persons.filter{…}
只返回List
,无法使用非空的name
和id
”来表示persons
,也无法在编译器内部表示它。用于组合filter
和map
:
persons.mapNotNull {
val id = it.id
val name = it.name
if (id != null && name != null) Pair(id, name) else null
}.toMap()
将id
和name
拉入局部变量应确保它们在对(id,name)
中被推断为非空,但可能不是必需的
您的方法不起作用的原因是persons.filter{…}
只返回List
,无法使用非空的name
和id
表示persons
列表,也无法在编译器内部表示它。顺便说一句,您甚至可以在mapNotNull
中删除:
persons.mapNotNull {
val id = it.id ?: return@mapNotNull null
val name = it.name ?: return@mapNotNull null
id to name
}.toMap()
顺便说一句,您甚至可以在mapNotNull
中删除:
persons.mapNotNull {
val id = it.id ?: return@mapNotNull null
val name = it.name ?: return@mapNotNull null
id to name
}.toMap()
也许你可以简单地改变
.map {
it.id to it.name
}
进入
后缀
运算符将String?
转换为String
,如果类型为String?
的值为null
,则引发异常,在本例中,由于先前应用的筛选器,该值不可能为真。
使用
应仅限于您负责明确声明值不能为null的情况:您对编译器说,值是String
,即使类型是String?
,也应谨慎使用。
编译器无法从传递给过滤器的谓词中推断字符串?
到字符串的类型域限制,但您可以,所以我认为代码>使用可能是一种有价值的方法…可能是,您可以简单地进行更改
.map {
it.id to it.name
}
进入
后缀
运算符将String?
转换为String
,如果类型为String?
的值为null
,则引发异常,在本例中,由于先前应用的筛选器,该值不可能为真。
使用
应仅限于您负责明确声明值不能为null的情况:您对编译器说,值是String
,即使类型是String?
,也应谨慎使用。
编译器无法从传递给过滤器的谓词中推断字符串?
到字符串的类型域限制,但您可以,所以我认为代码>使用是一种有价值的方法…我更喜欢mapNotNull
方法,原因有二:1。不创建不必要的中间列表(除非您使用序列
,在这种情况下,也不会过滤
+映射
);2.在未来的变化中,突破的可能性更小。我更喜欢mapNotNull
方法,原因有二:1。不创建不必要的中间列表(除非您使用序列
,在这种情况下,也不会过滤
+映射
);2.在未来的变化中突破的可能性更小。