I need to match the list and get the first non-zero element, and I need the display operation to be short, as it should be in the Java 8 threading API. Is there any ready-made way to do this in Kotlin without Java 8 threads?
I created my own extension method for this:
fun <T, R> Iterable<T>.firstNonNullMapping(transform: (T) -> R?): R? {
for (element in this) {
val result = transform(element)
if (result != null) {
return result
}
}
return null
}
The test proves that it works
val firstNonNullMapping = listOf(null, 'a', 'b')
.firstNonNullMapping {
assertNotEquals(it, 'b')
it
}
assertEquals(firstNonNullMapping, 'a')
IntelliJ, however, suggests that I am replacing the for loop with a tidier
return this
.map { transform(it) }
.firstOrNull { it != null }
The problem is that this will display all the elements of the iteration, and this is important for my use, which stops at the first non-empty element.
source
share