Kotlin List firstNotNullOf()
Syntax & Examples


Syntax of List.firstNotNullOf()

The syntax of List.firstNotNullOf() extension function is:

fun <T, R : Any> Iterable<T>.firstNotNullOf( transform: (T) -> R? ): R

This firstNotNullOf() 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 throws NoSuchElementException if no non-null value was produced.



✐ Examples

1 Example

In this example,

  • We create a list named list containing strings.
  • We use the firstNotNullOf extension function on list to find the first element whose length is greater than 5.
  • The result is printed to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf("apple", "banana", "orange", "kiwi", "mango");
    val result = list.firstNotNullOf { if (it.length > 5) it else null };
    println(result);
}

Output

banana

2 Example

In this example,

  • We create a list named list containing integers.
  • We use the firstNotNullOf extension function on list to find the first element greater than 25.
  • The result is printed to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(10, 20, 30, 40, 50);
    val result = list.firstNotNullOf { if (it > 25) it else null };
    println(result);
}

Output

30

3 Example

In this example,

  • We create a list named list containing characters.
  • We use the firstNotNullOf extension function on list to find the first element equal to 'c'.
  • The result is printed to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf('a', 'b', 'c', 'd', 'e');
    val result = list.firstNotNullOf { if (it == 'c') it else null };
    println(result);
}

Output

c

Summary

In this Kotlin tutorial, we learned about firstNotNullOf() extension function of List: the syntax and few working examples with output and detailed explanation for each example.