How to best implement a pattern where I want to co...
# getting-started
d
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
Copy code
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
Copy code
someCollection.mapNotNull {
    val result = someExpensiveComputation(it) ?: return@mapNotNull null
    it to result
}
you could golf that down to
Copy code
someCollection.mapNotNull { someExpensiveComputation(it)?.let(it::to) }
but I don't think it's clearer
d
Ah, I hate those early returns 🙂 Especially from lambdas
e
well you could write
Copy code
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
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.