The firstNotNullOfOrNull() extension function in Kotlin returns the first non-null value produced by the transform function applied to elements of a set in iteration order. If no non-null value is found, it returns null.
The syntax of Set.firstNotNullOfOrNull() extension function is:
fun <T, R : Any> Set<T>.firstNotNullOfOrNull(transform: (T) -> R?): R?
This firstNotNullOfOrNull() extension function of Set returns the first non-null value produced by the transform function being applied to elements of this collection in iteration order, or null if no non-null value was produced.
Parameter | Optional/Required | Description |
---|---|---|
transform | required | A function that takes an element and returns a nullable result. |
Set.firstNotNullOfOrNull() returns value of type R?
.
Using firstNotNullOfOrNull() to get the first non-null length of strings in a set.
For example,
fun main() {
val strings = setOf(null, "a", "ab", null, "abc")
val firstNonNullLength = strings.firstNotNullOfOrNull { it?.length }
println(firstNonNullLength)
}
1
Using firstNotNullOfOrNull() to get the first non-null square of integers in a set.
For example,
fun main() {
val numbers = setOf(null, 2, null, 3, 4)
val firstNonNullSquare = numbers.firstNotNullOfOrNull { it?.let { it * it } }
println(firstNonNullSquare)
}
4
Using firstNotNullOfOrNull() to get the first non-null value from a mixed set.
For example,
fun main() {
val mixedSet: Set<Any?> = setOf(null, "two", null, 3.0, 4)
val firstNonNullValue = mixedSet.firstNotNullOfOrNull { it }
println(firstNonNullValue)
}
"two"
In this Kotlin tutorial, we learned about firstNotNullOfOrNull() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.