What’s the preferred style to fallback to a defaul...
# announcements
j
What’s the preferred style to fallback to a default value when accessing a map?
map[key] ?: defaultValue
or
map.getOrDefault(key, defaultValue)
?
d
Depends on whether you values can be null I guess. (As suppose to not existing)
👍 2
m
I'd always go with
getOrDefault
It will always do what you want, and is easy to read.
j
I see. Thanks for your input. When using a map with a non-nullable value type, I find using the elvis much shorter, so I tend to favor it unless I need to call a method on the result. But maybe it’d be wiser to stick with
getOrDefault()
for general consistency.
t
Note:
getOrDefault
may be defined only when running Java 8 or more. Not a good fit for Android.
👍 1