first Not Null Of Or Null
inline fun <T, R : Any> Sequence<T>.firstNotNullOfOrNull(transform: (T) -> R?): R?
Content copied to clipboard
Returns the first non-null value produced by transform function being applied to elements of this sequence in iteration order, or null
if no non-null value was produced.
The operation is terminal.
Since Kotlin
1.5
Samples
import samples.*
import kotlin.test.*
fun main() {
//sampleStart
data class Rectangle(val height: Int, val width: Int) {
val area: Int get() = height * width
}
val rectangles = listOf(
Rectangle(3, 4),
Rectangle(1, 8),
Rectangle(6, 3),
Rectangle(4, 3),
Rectangle(5, 7)
)
val largeArea = rectangles.firstNotNullOf { it.area.takeIf { area -> area >= 15 } }
val largeAreaOrNull = rectangles.firstNotNullOfOrNull { it.area.takeIf { area -> area >= 15 } }
assertPrints(largeArea, "18")
assertPrints(largeAreaOrNull, "18")
assertFailsWith<NoSuchElementException> { val evenLargerArea = rectangles.firstNotNullOf { it.area.takeIf { area -> area >= 50 } } }
val evenLargerAreaOrNull = rectangles.firstNotNullOfOrNull { it.area.takeIf { area -> area >= 50 } }
assertPrints(evenLargerAreaOrNull, "null")
//sampleEnd
}