Different question: I want to return 1 if a map's ...
# getting-started
d
Different question: I want to return 1 if a map's value is not set or am empty list. Is there a more elegant way than:
Copy code
if (!myMap.containsKey(color) || myMap[color]!!.isEmpty()) return 1
m
Copy code
myMap[color]?.isEmpty() != false
d
Hmm, okay. I thought using the ? operator would skip the whole expression (and thus the whole if), if it encountered a null. But this means it evaluates to something... that is apparently not equal to false?
m
using the safe access operator does skip the rest of the expression, if the left side is null. But the
if
statement is not part of that expression. with the expression I wrote, you have several cases: 1. The item is not in the map, so you get
null?.isEmpty()
which evaluates to
null
, so
null != false -> true
2. the item is in the map, but it is empty, so you get
theEmptyItem?.isEmpty()
, which evaluates to
true
so
true != false -> true
3. the item is in the map and it is not empty, so you get
notEmptyItem?.isEmpty()
, which evaluates to
false
so
false != false -> false
d
Ah, so it basically 'evalutes' the expression to null, if any part is null. So
null?.something() == null
would be true? I get it, thanks. 🙂
m
yes that would be true:)
g
Just out of interest: Are you working on the Advent of Code puzzles? 🙂
d
Of course I am. 😛 This piece was for Day07 and I used it here (spoiler).
❤️ 1