Kotlin Short Circuit Card {}. FirstOrNull {}

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') // Mapping should be stopped before reaching '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.

+4
source share
2 answers

Kotlin sequences, Java 8, stream() asSequence():

return this
        .asSequence()
        .map { transform(it) }
        .firstOrNull { it != null }
+8

, , @ingoKegel, :

return this.firstOrNull { transform(it) != null }?.let { transform(it) }
0

Source: https://habr.com/ru/post/1666705/


All Articles