The syntax of Map.firstNotNullOf() extension function is:
fun <K, V, R : Any> Map<out K, V>.firstNotNullOf( transform: (Entry<K, V>) -> R? ): R
This firstNotNullOf() 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 throws NoSuchElementException if no non-null value was produced.
In this example,
map1
containing key-value pairs (1, 'a'), (2, null), (3, 'c')
.firstNotNullOf()
function on map1
, using the transform function { it.value }
to extract values.map1
is returned.fun main(args: Array<String>) {
val map1 = mapOf(1 to 'a', 2 to null, 3 to 'c');
val result = map1.firstNotNullOf { it.value }
print(result);
}
a
In this example,
map2
containing key-value pairs ('a', 1), ('b', null), ('c', 3)
.firstNotNullOf()
function on map2
, using the transform function { it.value }
to extract values.map2
is returned.fun main(args: Array<String>) {
val map2 = mapOf('a' to 1, 'b' to null, 'c' to 3);
val result = map2.firstNotNullOf { it.value }
print(result);
}
1
In this example,
map3
containing key-value pairs (1, 'apple'), (2, null), (3, 'cherry')
.firstNotNullOf()
function on map3
, using the transform function { it.value }
to extract values.map3
is returned.fun main(args: Array<String>) {
val map3 = mapOf(1 to "apple", 2 to null, 3 to "cherry");
val result = map3.firstNotNullOf { it.value }
print(result);
}
apple
In this Kotlin tutorial, we learned about firstNotNullOf() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.