Is there already a more idiomatic way to do this (...
# codingconventions
d
Is there already a more idiomatic way to do this (which is at least as efficient?):
Copy code
fun <T,R> Iterable<T>.firstMappedOrNull( mapping: (T)->R? ) : R? {
    for(element in this) {
        mapping(element)?.let { return it }
    }
    return null
}
r
foo.map { /*some transform*/ }.find { it != null }
m
Using a sequence:
Copy code
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
Ah, I didn’t realize that, good catch
y
Copy code
foo.mapNotNull(mapping).firstOrNull()
d
@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