https://kotlinlang.org logo
Title
p

poohbar

07/02/2019, 7:07 PM
hi!
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

Dico

07/02/2019, 7:13 PM
Perhaps you can do
mapNotNull
to
Pair?
and then invoke
.toMap()
p

Pavlo Liapota

07/02/2019, 7:14 PM
Yes, something like this:
columns
    .mapNotNull { (id, direction) ->
        if (direction == null) null else id to direction
    }
    .toMap()
d

Dico

07/02/2019, 7:15 PM
(id, dir) -> dir?.let { Pair(id, it) }
p

Pavlo Liapota

07/02/2019, 7:15 PM
Even better 🙂
d

Dico

07/02/2019, 7:17 PM
But i think the OP 's code is more readable
k

karelpeeters

07/02/2019, 7:21 PM
Consider also whether this even matters, if you only use
map.get
a missing entry and a null value behave the same.
p

Pavlo Liapota

07/02/2019, 7:25 PM
Also I prefer to use
associate
instead of
associateBy
in such cases:
.associate { it.id to it.direction!! }
p

poohbar

07/02/2019, 7:27 PM
thank you all