gpt4 book ai didi

nullpointerexception - 在 Kotlin 的 map 函数中检查 null

转载 作者:行者123 更新时间:2023-12-02 12:17:02 25 4
gpt4 key购买 nike

我是 Kotlin 的新手,我想将一个对象 (ProductVisibility) 映射到另一个对象 (fmpProduct) 上。某些对象无法转换,因此我需要在某些情况下跳过它们。

我想知道是否有比我使用过滤器和“!!”更好的方法来做到这一点我觉得它被黑客入侵了。我错过了什么吗?

val newCSProductVisibility = fmpProducts
.filter { parentIdGroupedByCode.containsKey(it.id) }
.filter { ProductType.fromCode(it.type) != null } //voir si on accumule les erreus dans une variable à montrer
.map {
val type = ProductType.fromCode(it.type)!! //Null already filtered
val userGroupIds = type.productAvailabilityUserGroup.map { it.id }.joinToString(",")
val b2bGroupIds = type.b2bUserGroup.map { it.id }.joinToString { "," }
val b2bDescHide = !type.b2bUserGroup.isEmpty()
val parentId = parentIdGroupedByCode[it.id]!! //Null already filtered

CSProductDao.ProductVisibility(parentId, userGroupIds, b2bGroupIds, b2bDescHide)
}

编辑:更新了 map 访问,如建议的评论

最佳答案

使用 mapNotNull()避免 filter() s 并在 mapNotNull() 中执行所有操作块,然后自动类型转换为 non-null类型作品。
例子:

fun f() {

val list = listOf<MyClass>()

val v = list.mapNotNull {
if (it.type == null) return@mapNotNull null
val type = productTypeFromCode(it.type)
if (type == null) return@mapNotNull null
else MyClass2(type) // type is automatically casted to type!! here
}


}

fun productTypeFromCode(code: String): String? {
return null
}


class MyClass(val type: String?, val id: String)

class MyClass2(val type: String)

关于nullpointerexception - 在 Kotlin 的 map 函数中检查 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45969989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com