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
listcontaining elements1, 2, 3, 4, 5. - We use the
requireNoNullsfunction returns a new list if there are non null elements only. - The resulting list is stored in
result. - We print
resultusingprintln().
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
listcontaining elements'a', 'b', null, 'd', 'e'. - We use the
requireNoNullsfunction. Since there is anullelement 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.