Kotlin List requireNoNulls()
Syntax & Examples


Syntax of List.requireNoNulls()

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

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

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



✐ Examples

1 Example

In this example,

  • We create a list of integers named list containing elements 1, 2, 3, 4, 5.
  • We use the requireNoNulls function returns a new list if there are non null elements only.
  • The resulting list is stored in result.
  • We print result using println().

Kotlin Program

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

Output

[1, 2, 3, 4, 5]

2 Example

In this example,

  • We create a list of characters named list containing elements 'a', 'b', null, 'd', 'e'.
  • We use the requireNoNulls function. Since there is a null element in the list, the function throws IllegalArgumentException.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf('a', 'b', null, 'd', 'e')
    val result = list.requireNoNulls()
    println(result)
}

Output

Exception in thread "main" java.lang.IllegalArgumentException: null element found in [a, b, null, d, e].

Summary

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