hi! ``` list.filter { it.field != null } .asso...
# getting-started
p
hi!
Copy code
list.filter { it.field != null }
    .associateBy({ it.id }, { it.field!! })
is there a way to avoid
!!
on the second line?
list
is a list of:
data class Person(val id: String, val field: Field?)
d
Perhaps you can do
mapNotNull
to
Pair?
and then invoke
.toMap()
p
Yes, something like this:
Copy code
columns
    .mapNotNull { (id, direction) ->
        if (direction == null) null else id to direction
    }
    .toMap()
d
(id, dir) -> dir?.let { Pair(id, it) }
p
Even better 🙂
d
But i think the OP 's code is more readable
k
Consider also whether this even matters, if you only use
map.get
a missing entry and a null value behave the same.
p
Also I prefer to use
associate
instead of
associateBy
in such cases:
Copy code
.associate { it.id to it.direction!! }
p
thank you all