firstNotNullOfOrNull所在位置是kotlin.sequences.firstNotNullOfOrNull,其相关用法介绍如下。

用法:

inline fun <T, R : Any> Sequence<T>.firstNotNullOfOrNull(
    transform: (T) -> R?
): R?

返回由 transform 函数生成的第一个非空值,该函数按迭代顺序应用于此序列的元素,如果没有生成非空值,则返回 null

操作是 terminal

例子:

import kotlin.test.*

fun main(args: Array<String>) {
//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 } }

println(largeArea) // 18
println(largeAreaOrNull) // 18

// val evenLargerArea = rectangles.firstNotNullOf { it.area.takeIf { area -> area >= 50 } } // will fail with NoSuchElementException
val evenLargerAreaOrNull = rectangles.firstNotNullOfOrNull { it.area.takeIf { area -> area >= 50 } }

println(evenLargerAreaOrNull) // null
//sampleEnd
}

输出:

18
18
null