BIS Tech
BIS Tech

Reputation: 19514

kotlin null handle in map to data class

bigPicture is null sometimes. how to handle this?

App crash : java.util.NoSuchElementException: Key bigPicture is missing in the map.

data class NotificationModel(val version: String?,
                             val bigPicture: String?,
                             val title: String?,
                             val body: String?,
                             val messageData:String?,
                             val groupKey: String?) {
    companion object {
        fun from(map: Map<String?, String?>) = object {
            val version by map
            val bigPicture by map
            val title by map
            val body by map
            val groupKey by map
            val messageData by map

            val data = NotificationModel(version, bigPicture, title, body,messageData, groupKey)
        }.data
    }
}

Upvotes: 0

Views: 1816

Answers (3)

Anis MARZOUK
Anis MARZOUK

Reputation: 286

In Kotlin they provide two methods for getting value from a Map

  1. myMap.get(key) or mayMap[key] : returns the value if it exists or returns null if it doesn't
  2. myMap.getValue(key): returns the value for the key or throws an NoSuchElementException if the key does not exist.

Upvotes: 2

xjcl
xjcl

Reputation: 15339

This kind of null check is what the Elvis operator is for:

val bigPicture = map["bigPicture"] ?: ""

Upvotes: 1

NRUSINGHA MOHARANA
NRUSINGHA MOHARANA

Reputation: 1559

If key is not present in the map then only we get java.util.NoSuchElementException: Key bigPicture is missing in the map. Look:

    val map = mutableMapOf<String?,String?>()
    map["version"] = "1.1"
    //map["bigPicture"] = "my BigPic" // app crash because no key is present
    map["bigPicture"] = null  // No crash here as key is present but value is null
    map["title"] = "My Title"
    map["body"] = "My Body"
    map["groupKey"] = "Group key"
    map["messageData"] = "My Msg Data"
    val notificationModel = NotificationModel.from(map)
    Log.d("TAG==>>","BigPicture = ${notificationModel.bigPicture}  ")
}

To avoid crash you may try below code:

    data class NotificationModel(val version: String?,
                             val bigPicture: String?,
                             val title: String?,
                             val body: String?,
                             val messageData:String?,
                             val groupKey: String?) {
    companion object {
        fun from(map: MutableMap<String?, String?>) = object {
            val version by map
            val bigPicture = if (map.containsKey("bigPicture")) map["bigPicture"] else ""
            val title by map
            val body by map
            val groupKey by map
            val messageData by map

            val data = NotificationModel(version, bigPicture, title, body,messageData, groupKey)
        }.data
    }
}

Upvotes: 1

Related Questions