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.
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.
Set.requireNoNulls() returns value of type Set
.
Using requireNoNulls() to ensure a set of integers has no null elements, throwing an exception if any null elements are found.
For example,
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}")
}
}
Exception: null element found in collection
Using requireNoNulls() to ensure a set of strings has no null elements, throwing an exception if any null elements are found.
For example,
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}")
}
}
Exception: null element found in collection
Using requireNoNulls() to ensure a set of custom objects has no null elements, throwing an exception if any null elements are found.
For example,
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}")
}
}
Exception: null element found in collection
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.