2017-08-30 62 views
2

我是Kotlin的新手,我想將一個對象(ProductVisibility)映射到另一個對象(fmpProduct)上。某些對象無法轉換,因此我需要在某些情況下跳過它們。在Kotlin中檢查地圖函數中的null

我想知道是否有更好的方法來做到這一點,而不是我用過濾器和「!!」做的事情。我覺得它被黑了。我錯過了什麼嗎?

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

編輯:更新贊評論地圖訪問建議

+0

要讀取地圖值,你應該使用數組註解來替代:parentIdGroupedByCode [it.id] – BladeCoder

+0

我更新地圖,就像你說的感謝訪問它,但它仍然可空 – Mike

回答

2

使用mapNotNull()避免filter() S和在mapNotNull()塊做的一切,然後自動強制轉換爲non-null類型的作品。 例子:

fun f() { 

    val list = listOf<MyClass>() 

    val v = list.mapNotNull { 
     if (it.type == null) [email protected] null 
     val type = productTypeFromCode(it.type) 
     if (type == null) [email protected] 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) 
+0

我沒不知道mapNotNull。但什麼是return @ mapNotNull null。當我嘗試了你的代碼的時候,但是當我嘗試使用我的代碼時,我不得不將它添加到我的返回對象中,因爲出現了一個轉換錯誤,我不知道它來自哪裏。返回@ mapNotNull CSProductDao.ProductVisibility(parentId,userGroupIds,b2bGroupIds,b2bDescHide)我找不到@mapNotNull上的文檔,我的搜索結果越來越差: – Mike

+1

我找到了我的答案,它是一個返回標籤,它有道理:https: //kotlinlang.org/docs/reference/returns.html#return-at-labels – Mike