Kotlin Tutorials

Kotlin Set requireNoNulls()
Syntax & Examples

Set.requireNoNulls() extension function

The requireNoNulls() extension function in Kotlin returns an original collection containing all the non-null elements, throwing an IllegalArgumentException if there are any null elements.


Syntax of Set.requireNoNulls()

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

fun <T : Any> Set<T?>.requireNoNulls(): Set<T>

This requireNoNulls() extension function of Set returns an original collection containing all the non-null elements, throwing an IllegalArgumentException if there are any null elements.

Return Type

Set.requireNoNulls() returns value of type Set.



✐ Examples

1 Ensuring a set of integers has no null elements

Using requireNoNulls() to ensure a set of integers has no null elements, throwing an exception if any null elements are found.

For example,

  1. Create a set of nullable integers.
  2. Use requireNoNulls() to ensure there are no null elements in the set.
  3. Print the resulting set.

Kotlin Program

fun main() {
    val numbers: Set<Int?> = setOf(1, 2, 3, null)
    try {
        val result = numbers.requireNoNulls()
        println(result)
    } catch (e: IllegalArgumentException) {
        println("Exception: ${e.message}")
    }
}

Output

Exception: null element found in collection

2 Ensuring a set of strings has no null elements

Using requireNoNulls() to ensure a set of strings has no null elements, throwing an exception if any null elements are found.

For example,

  1. Create a set of nullable strings.
  2. Use requireNoNulls() to ensure there are no null elements in the set.
  3. Print the resulting set.

Kotlin Program

fun main() {
    val strings: Set<String?> = setOf("one", "two", null, "three")
    try {
        val result = strings.requireNoNulls()
        println(result)
    } catch (e: IllegalArgumentException) {
        println("Exception: ${e.message}")
    }
}

Output

Exception: null element found in collection

3 Ensuring a set of custom objects has no null elements

Using requireNoNulls() to ensure a set of custom objects has no null elements, throwing an exception if any null elements are found.

For example,

  1. Create a data class.
  2. Create a set of nullable custom objects.
  3. Use requireNoNulls() to ensure there are no null elements in the set.
  4. Print the resulting set.

Kotlin Program

data class Person(val name: String, val age: Int)

fun main() {
    val people: Set<Person?> = setOf(Person("Alice", 30), null, Person("Charlie", 35))
    try {
        val result = people.requireNoNulls()
        println(result)
    } catch (e: IllegalArgumentException) {
        println("Exception: ${e.message}")
    }
}

Output

Exception: null element found in collection

Summary

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