Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for null in map function in Kotlin

I'm new to Kotlin and I want to map an object (ProductVisibility) base on another one (fmpProduct). Some object can't be converted so I need to skip them on some condition.

I wanted to know if there's a better way to do this than what I did with the filter and the "!!" I feel that it's hacked. Am I missing something ?

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

edit: updated the map access like comment suggested

like image 755
Mike Avatar asked Aug 30 '17 21:08

Mike


1 Answers

Use mapNotNull() to avoid the filter()s and do everything in the mapNotNull() block, then the automatic typecast to non-null type works. Example:

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)
like image 184
fweigl Avatar answered Sep 28 '22 11:09

fweigl