Kotlin Tutorials

Kotlin Map firstNotNullOfOrNull()
Syntax & Examples

Syntax of Map.firstNotNullOfOrNull()

The syntax of Map.firstNotNullOfOrNull() extension function is:

fun <K, V, R : Any> Map<out K, V>.firstNotNullOfOrNull( transform: (Entry<K, V>) -> R? ): R?

This firstNotNullOfOrNull() extension function of Map returns the first non-null value produced by transform function being applied to entries of this map in iteration order, or null if no non-null value was produced.



✐ Examples

1 Get the first letter value

In this example,

  • We create a map named map1 containing pairs of numbers and characters.
  • We apply the firstNotNullOfOrNull() function on map1, transforming each entry into its corresponding character value and returning the first non-null letter value, or null if no such value exists.
  • The resulting value is printed to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map1 = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
    val result1 = map1.firstNotNullOfOrNull { (_, value) -> value.takeIf { it.isLetter() } }
    println(result1)
}

Output

a

2 Get the first value greater than 1

In this example,

  • We create a map named map2 containing pairs of characters and numbers.
  • We apply the firstNotNullOfOrNull() function on map2, transforming each entry into its corresponding number value and returning the first non-null value greater than 1, or null if no such value exists.
  • The resulting value is printed to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map2 = mapOf('a' to 1, 'b' to 2, 'c' to 3)
    val result2 = map2.firstNotNullOfOrNull { (_, value) -> value.takeIf { it > 1 } }
    println(result2)
}

Output

2

3 Get the first even number value

In this example,

  • We create a map named map3 containing pairs of strings and numbers.
  • We apply the firstNotNullOfOrNull() function on map3, transforming each entry into its corresponding number value and returning the first non-null even number value, or null if no such value exists.
  • The resulting value is printed to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map3 = mapOf("apple" to 5, "banana" to 6, "cherry" to 7)
    val result3 = map3.firstNotNullOfOrNull { (_, value) -> value.takeIf { it % 2 == 0 } }
    println(result3)
}

Output

6

Summary

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