Kotlin List firstOrNull()
Syntax & Examples


Syntax of List.firstOrNull()

There are 2 variations for the syntax of List.firstOrNull() extension function. They are:

1.
fun <T> List<T>.firstOrNull(): T?

This extension function returns the first element, or null if the list is empty.

2.
fun <T> Iterable<T>.firstOrNull( predicate: (T) -> Boolean ): T?

This extension function returns the first element matching the given predicate, or null if element was not found.



✐ Examples

1 Example

In this example,

  • We create a list named list1 containing strings.
  • We use the firstOrNull function on list1 to get the first element or null if the list is empty.
  • The first element of list1 is stored in result.
  • Finally, we print the value of result to standard output using the println statement.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf("apple", "banana", "cherry")
    val result = list1.firstOrNull()
    println(result)
}

Output

apple

2 Example

In this example,

  • We create a list named list2 containing integers.
  • We use the firstOrNull function on list2 with a predicate that checks if an element is greater than 10.
  • Since there is no element of list2 that satisfies the predicate, null is returned and stored in result.
  • Finally, we print the value of result to standard output using the println statement.

Kotlin Program

fun main(args: Array<String>) {
    val list2 = listOf(1, 2, 3, 4, 5)
    val result = list2.firstOrNull { it > 10 }
    println(result)
}

Output

null

3 Example

In this example,

  • We create a list named list3 containing strings.
  • We use the firstOrNull function on list3 with a predicate that checks if a string's length is greater than 5.
  • The first element of list3 that satisfies the predicate is stored in result.
  • Finally, we print the value of result to standard output using the println statement.

Kotlin Program

fun main(args: Array<String>) {
    val list3 = listOf("hello", "world")
    val result = list3.firstOrNull { it.length > 5 }
    println(result)
}

Output

hello

Summary

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