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
Milan Hruban
12/12/2020, 5:20 PM
Copy code
myMap[color]?.isEmpty() != false
d
Draget
12/12/2020, 5:23 PM
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
Milan Hruban
12/12/2020, 5:45 PM
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
Draget
12/12/2020, 5:47 PM
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
Milan Hruban
12/12/2020, 5:48 PM
yes that would be true:)
g
georg
12/12/2020, 8:45 PM
Just out of interest: Are you working on the Advent of Code puzzles? 🙂