在 Kotlin 的 map 函数中检查 null

Mik*_*ike 5 nullpointerexception kotlin

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

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

asc*_*sco 7

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

  • 我找到了我的答案。这是一个退货标签,这是有道理的:https://kotlinlang.org/docs/reference/returns.html#return-at-labels (3认同)