https://kotlinlang.org logo
Title
d

darkmoon_uk

05/21/2019, 2:11 PM
Is there already a more idiomatic way to do this (which is at least as efficient?):
fun <T,R> Iterable<T>.firstMappedOrNull( mapping: (T)->R? ) : R? {
    for(element in this) {
        mapping(element)?.let { return it }
    }
    return null
}
r

rook

05/21/2019, 2:13 PM
foo.map { /*some transform*/ }.find { it != null }
m

marstran

05/21/2019, 2:22 PM
Using a sequence:
return asSequence()
  .map(mapping)
  .find { it != null }
I think the null check has to be on the result of the call to
mapping
@rook
r

rook

05/21/2019, 2:25 PM
Ah, I didn’t realize that, good catch
y

Yossi Saiada

07/16/2019, 1:04 PM
foo.mapNotNull(mapping).firstOrNull()
d

darkmoon_uk

07/17/2019, 1:11 PM
@Yossi Saiada That is concise but less efficient - in your solution all values will be mapped before the first is picked. @marstran’s solution addresses that requirement with a
Sequence
- where sequence operators generally act like builders, deferring computation of each element until there's an operator that forces the value to resolve e.g.
.toList()
.
👍 1