Kotlin Tutorials

Kotlin Set firstNotNullOf()
Syntax & Examples

Set.firstNotNullOf() extension function

The firstNotNullOf() extension function in Kotlin returns the first non-null value produced by the transform function applied to elements of a set in iteration order. If no non-null value is found, it throws a NoSuchElementException.


Syntax of Set.firstNotNullOf()

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

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

This firstNotNullOf() extension function of Set returns the first non-null value produced by the transform function being applied to elements of this collection in iteration order, or throws NoSuchElementException if no non-null value was produced.

Parameters

ParameterOptional/RequiredDescription
transformrequiredA function that takes an element and returns a nullable result.

Return Type

Set.firstNotNullOf() returns value of type R.



✐ Examples

1 Finding the first non-null length of a string

Using firstNotNullOf() to get the first non-null length of strings in a set.

For example,

  1. Create a set of strings including null values.
  2. Define a transform function that returns the length of a string or null if the string is null.
  3. Use firstNotNullOf() to get the first non-null length from the set.
  4. Print the resulting length.

Kotlin Program

fun main() {
    val strings = setOf(null, "a", "ab", null, "abc")
    val firstNonNullLength = strings.firstNotNullOf { it?.length }
    println(firstNonNullLength)
}

Output

1

2 Finding the first non-null square of an integer

Using firstNotNullOf() to get the first non-null square of integers in a set.

For example,

  1. Create a set of integers including null values.
  2. Define a transform function that returns the square of an integer or null if the integer is null.
  3. Use firstNotNullOf() to get the first non-null square from the set.
  4. Print the resulting square.

Kotlin Program

fun main() {
    val numbers = setOf(null, 2, null, 3, 4)
    val firstNonNullSquare = numbers.firstNotNullOf { it?.let { it * it } }
    println(firstNonNullSquare)
}

Output

4

3 Finding the first non-null value from a mixed set

Using firstNotNullOf() to get the first non-null value from a mixed set.

For example,

  1. Create a set of mixed types including null values.
  2. Define a transform function that returns a non-null value or null if the element is null.
  3. Use firstNotNullOf() to get the first non-null value from the set.
  4. Print the resulting value.

Kotlin Program

fun main() {
    val mixedSet: Set<Any?> = setOf(null, "two", null, 3.0, 4)
    val firstNonNullValue = mixedSet.firstNotNullOf { it }
    println(firstNonNullValue)
}

Output

"two"

Summary

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