Issue
I am parsing a Firebase DataSnapshot
(json) object into a data class. Instead of the following, can I combine them and return if any one of them is null? Something like Swift's guard let ..., let ... else { return }
func parse(snapshot: DataSnapshot) {
val type = snapshot.child("type").value as? String ?: return
val unitType = UnitEnumType.values().firstOrNull { it.abbrv == type } ?: return
val imageUrl = snapshot.child("image_url").value as? String ?: return
...
}
Solution
You can write
val (type, unitType, imageUrl) = Triple(
snapshot.child("type").value as? String ?: return,
UnitEnumType.values().firstOrNull { it.abbrv == "a" } ?: return,
snapshot.child("image_url").value as? String ?: return
)
However, you can't refer to type
(the result of the first expression) in the second expression. This is an all-or-nothing assignment.
Answered By - Marko Topolnik
Answer Checked By - Gilberto Lyons (JavaFixing Admin)