在Kotlin中检查map函数中的null

时间:2017-08-30 21:30:32

标签: nullpointerexception kotlin

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

我想知道是否有更好的方法来做到这一点,而不是我对过滤器和" !!"我觉得它被黑了。我错过了什么吗?

$ awk -f tst.awk file
When chapman billies leave the street,
And drouthy neibors, neibors, meet;
As market days are wearing late,
And folk begin to tak the gate,
While we sit bousing at the nappy,
An' getting fou and unco happy,

    define host {
        host_name   drac.vs2.xxx.yyy
        address     10.5.220.48
        use         yyy-drac
        parents     router.xxx.yyy

    }

We think na on the lang Scots miles,
The mosses, waters, slaps and stiles,
That lie between us and our hame,
Where sits our sulky, sullen dame,
Gathering her brows like gathering storm,
Nursing her wrath to keep it warm.

 - Tam O'Shanter by Robert Burns

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

1 个答案:

答案 0 :(得分:2)

使用mapNotNull()来避免filter()并执行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)