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
list1containing strings. - We use the
firstNotNullOfOrNullfunction onlist1with 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
list1is stored inresult. - Finally, we print the value of
resultto standard output using theprintlnstatement.
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
list2containing integers and a null value. - We use the
firstNotNullOfOrNullfunction onlist2with a transform function that returns the element itself. - The first non-null value produced by the transform function on
list2is stored inresult. - Finally, we print the value of
resultto standard output using theprintlnstatement.
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
list3containing strings and a null value. - We use the
firstNotNullOfOrNullfunction onlist3with a transform function that converts each string to uppercase, handling null values safely. - The first non-null value produced by the transform function on
list3is stored inresult. - Finally, we print the value of
resultto standard output using theprintlnstatement.
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.