Kotlin List firstNotNullOfOrNull()
Syntax & Examples
Syntax of List.firstNotNullOfOrNull()
The syntax of List.firstNotNullOfOrNull() extension function is:
fun <T, R : Any> Iterable<T>.firstNotNullOfOrNull( transform: (T) -> R? ): R?
This firstNotNullOfOrNull() extension function of List returns the first non-null value produced by transform function being applied to elements of this collection in iteration order, or null if no non-null value was produced.
✐ Examples
1 Example
In this example,
- We create a list named
list1
containing strings. - We use the
firstNotNullOfOrNull
function onlist1
with a transform function that returns the string if its length is greater than 5, otherwise null. - The first non-null value produced by the transform function on
list1
is stored inresult
. - Finally, we print the value of
result
to standard output using theprintln
statement.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("apple", "banana", "cherry")
val result = list1.firstNotNullOfOrNull { if (it.length > 5) it else null }
println(result)
}
Output
banana
2 Example
In this example,
- We create a list named
list2
containing integers and a null value. - We use the
firstNotNullOfOrNull
function onlist2
with a transform function that returns the element itself. - The first non-null value produced by the transform function on
list2
is stored inresult
. - Finally, we print the value of
result
to standard output using theprintln
statement.
Kotlin Program
fun main(args: Array<String>) {
val list2 = listOf(1, 2, 3, null, 5)
val result = list2.firstNotNullOfOrNull { it }
println(result)
}
Output
1
3 Example
In this example,
- We create a list named
list3
containing strings and a null value. - We use the
firstNotNullOfOrNull
function onlist3
with a transform function that converts each string to uppercase, handling null values safely. - The first non-null value produced by the transform function on
list3
is stored inresult
. - Finally, we print the value of
result
to standard output using theprintln
statement.
Kotlin Program
fun main(args: Array<String>) {
val list3 = listOf("hello", null, "world")
val result = list3.firstNotNullOfOrNull { it?.toUpperCase() }
println(result)
}
Output
HELLO
Summary
In this Kotlin tutorial, we learned about firstNotNullOfOrNull() extension function of List: the syntax and few working examples with output and detailed explanation for each example.