anybody knows a nicer way to do this: ``` ...
# getting-started
j
anybody knows a nicer way to do this:
Copy code
val childUnitsById = units
                .map { if(it.parent != null) it else null }
                .filterNotNull()
                .groupBy {it.parent!!}
a
jaspersmit: use
mapNotNull { }
j
great that that exists:)
so then we have
Copy code
val childUnitsById = units
                .mapNotNull { if(it.parent != null) it else null }
                .groupBy {it.parent!!}
No suggestions? 😛
m
wasn't a good one haha
j
thats unfortunate 😞
m
but why do you need to map first?
a
@jaspersmit is it correct that you are just filtering by
parent != null
and then group them together? you could do that with
filter { it.parent != null }
too
m
exactly what I was thinking
j
yes you're right but i was looking for something to avoid the !!
but i was not very succesful with that
m
ooh, yeah, I don't think there's a way to smart cast it
j
i realize i need a groupByNotNull
m
However I think this is a pretty-self contained case of the !! operator
I'd go forward with this
j
yes i will do that 🙂
c
The only way to get rid of
!!
would be to create a
List<ParentType>
(not nullable), so you'd have to generate that list first. Means you'd iterate twice, but you'd get rid of the
!!
.
If you know that list is small compared to the original list, probably worth doing. If not, your initial code is fine
Do keep in mind that technically, you can still get an NPE (i.e. if another thread sets one of these parents to
null
by the time you get there)
j
luckily parent is immutable
g
this seems to work fine for me, no
!!
needed
Copy code
val childUnitsById = units
            .filter { it.parent != null }
            .groupBy { it.parent }
c
What's the type of
it.parent
?
g
Copy code
data class Node(val parent: Node?, val id: String) {
    override fun toString(): String {
        return "Node(id='$id')"
    }
}