https://kotlinlang.org logo
#android
Title
# android
a

Ayden

08/01/2018, 11:57 AM
How to replace this
if
statement with Alvis Operator?
Copy code
if (element == null) {
    return null
}
val validationObject = element.asJsonObject
val validation: MutableMap<String, String> = HashMap()
for (entry: Map.Entry<String, JsonElement> in validationObject.entrySet()) {
    val key: String = entry.key
    val value: String = entry.value.asString
    validation.put(key, value)
}
l

Lucas Ł

08/01/2018, 12:02 PM
?:
(`e`lvis operator) gives you either a default value or default behaviour https://kotlinlang.org/docs/reference/null-safety.html#elvis-operator The only thing I can see from your snippet that can be null is
element
Copy code
val validationObject = element?.asJsonObject ?: JsonObject()
val validation: MutableMap<String, String> = HashMap()
for (entry: Map.Entry<String, JsonElement> in validationObject.entrySet()) {
    val key: String = entry.key
    val value: String = entry.value.asString
    validation.put(key, value)
}
if you don't want the code below do an 'empty run' you can also just do something like:
val validationObject = element?.asJsonObject ?: return
if your function doesn't return any value
3 Views