https://kotlinlang.org logo
Title
d

David Kubecka

03/09/2023, 1:26 PM
How to best implement a pattern where I want to compute a value for each element in a collection and return those element+value pairs where the value is not null)? Currently, I have simply this
someCollection.map { it to someExpensiveComputation(it) }.filter { it.second != null }
which works but the return type is
List<T, R?>
and I of course want
List<T, R>
.
e

ephemient

03/09/2023, 1:27 PM
someCollection.mapNotNull {
    val result = someExpensiveComputation(it) ?: return@mapNotNull null
    it to result
}
you could golf that down to
someCollection.mapNotNull { someExpensiveComputation(it)?.let(it::to) }
but I don't think it's clearer
d

David Kubecka

03/09/2023, 1:31 PM
Ah, I hate those early returns 🙂 Especially from lambdas
e

ephemient

03/09/2023, 1:32 PM
well you could write
if (result != null) it to result else null
or the equivalent
?.let
if you wanted, I just prefer the early return to the additional nested scope
d

David Kubecka

03/09/2023, 1:36 PM
Well, I probably prefer your second solution, although I would just use the infix
to
(have to invent an alias for the inner
it
, though). Btw it didn't occur to me that it can be used this way in its prefix variant but of course it makes sense.