The all() extension function for sets in Kotlin returns true if all elements in the set match the given predicate.
The syntax of Set.all() extension function is:
fun <T> Set<T>.all(predicate: (T) -> Boolean): Boolean
This all() extension function of Set returns true if all elements match the given predicate.
Parameter | Optional/Required | Description |
---|---|---|
predicate | required | A function that takes an element of the set and returns a Boolean indicating if the element matches the condition. |
Set.all() returns value of type Boolean
.
In Kotlin, we can use the all()
function to check if all elements in a set of integers are even.
For example,
all()
function with a predicate that checks if each element is even.println
function.fun main(args: Array<String>) {
val numbers = setOf(2, 4, 6, 8, 10)
val allEven = numbers.all { it % 2 == 0 }
println("Are all numbers even? $allEven")
}
Are all numbers even? true
In Kotlin, we can use the all()
function to check if all elements in a set of strings have a length greater than 3.
For example,
all()
function with a predicate that checks if each string has a length greater than 3.println
function.fun main(args: Array<String>) {
val fruits = setOf("apple", "banana", "cherry")
val allLong = fruits.all { it.length > 3 }
println("Do all fruits have length greater than 3? $allLong")
}
Do all fruits have length greater than 3? true
In Kotlin, we can use the all()
function on an empty set, which will return true as there are no elements to fail the predicate.
For example,
all()
function with a predicate that checks if each element is positive.println
function.fun main(args: Array<String>) {
val emptySet = emptySet<Int>()
val allPositive = emptySet.all { it > 0 }
println("Are all numbers positive in the empty set? $allPositive")
}
Are all numbers positive in the empty set? true
In this Kotlin tutorial, we learned about all() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.