https://kotlinlang.org logo
Title
j

jaspersmit

05/29/2017, 12:28 PM
anybody knows a nicer way to do this:
val childUnitsById = units
                .map { if(it.parent != null) it else null }
                .filterNotNull()
                .groupBy {it.parent!!}
a

Andreas Sinz

05/29/2017, 12:33 PM
jaspersmit: use
mapNotNull { }
j

jaspersmit

05/29/2017, 12:34 PM
great that that exists:)
so then we have
val childUnitsById = units
                .mapNotNull { if(it.parent != null) it else null }
                .groupBy {it.parent!!}
No suggestions? 😛
m

menegatti

05/29/2017, 12:38 PM
wasn't a good one haha
j

jaspersmit

05/29/2017, 12:38 PM
thats unfortunate 😞
m

menegatti

05/29/2017, 12:38 PM
but why do you need to map first?
a

Andreas Sinz

05/29/2017, 12:39 PM
@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

menegatti

05/29/2017, 12:39 PM
exactly what I was thinking
j

jaspersmit

05/29/2017, 12:39 PM
yes you're right but i was looking for something to avoid the !!
but i was not very succesful with that
m

menegatti

05/29/2017, 12:42 PM
ooh, yeah, I don't think there's a way to smart cast it
j

jaspersmit

05/29/2017, 12:44 PM
i realize i need a groupByNotNull
m

menegatti

05/29/2017, 12:50 PM
However I think this is a pretty-self contained case of the !! operator
I'd go forward with this
j

jaspersmit

05/29/2017, 12:59 PM
yes i will do that 🙂
c

cedric

05/29/2017, 2:27 PM
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

jaspersmit

05/29/2017, 2:40 PM
luckily parent is immutable
g

gjesse

05/29/2017, 4:44 PM
this seems to work fine for me, no
!!
needed
val childUnitsById = units
            .filter { it.parent != null }
            .groupBy { it.parent }
c

cedric

05/29/2017, 4:45 PM
What's the type of
it.parent
?
g

gjesse

05/29/2017, 4:46 PM
data class Node(val parent: Node?, val id: String) {
    override fun toString(): String {
        return "Node(id='$id')"
    }
}