a question, how to write `if (a.city != null) city...
# getting-started
ł
a question, how to write
if (a.city != null) city = a.city!!
in a kotlin idiomatic way?
s
Well, there’s always
a.city?.let { city = it }
. Not sure how much I like it, though.
1
g
The first one is dangerous because in a multithreaded app
a.city
could have been mutated after the check but before the access, resulting in a NullPointerException. The suggestion by @Sam is better
s
You could also write
city = a.city ?: city
, which should achieve the same effect as long as reassigning
city
doesn’t have side effects
g
Best not to use mutable fields or variables altogether!
11