在 Kotlin 的 map 函数中检查 null。

7

我是 Kotlin 的新手,想要根据另一个对象(fmpProduct)映射一个对象(ProductVisibility)。有些对象无法转换,因此我需要在某些条件下跳过它们。

我想知道是否有比我用过滤器和 "!!" 更好的方法。我觉得这样做有点 hack。我是不是漏掉了什么?

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)
            }

编辑:根据评论建议更新了地图访问方式


为了读取地图值,您应该使用数组注释而不是 parentIdGroupedByCode[it.id]。 - BladeCoder
我按照你说的更新了地图以便访问,谢谢。但它仍然是可空的。 - Mike
1个回答

10
使用mapNotNull()可以避免使用filter(),并将所有操作都放在mapNotNull()块中,这样自动类型转换为非空类型就可以起作用。 示例:
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)

1
我之前不知道mapNotNull。但是return@mapNotNull null是什么意思呢?当我尝试你的代码时,它可以工作,但是当我用我的代码尝试时,我不得不将它添加到我的返回对象中,因为有一个转换错误,我不知道它来自哪里。return@mapNotNull CSProductDao.ProductVisibility(parentId, userGroupIds, b2bGroupIds, b2bDescHide)。我找不到关于@mapNotNull的文档,我的谷歌搜索越来越差了:( - Mike
3
我找到了答案。它是一个返回标签,有意义:https://kotlinlang.org/docs/reference/returns.html#return-at-labels - Mike

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接