Kotlin List all()
Syntax & Examples
Syntax of List.all()
The syntax of List.all() extension function is:
fun <T> Iterable<T>.all(predicate: (T) -> Boolean): BooleanThis all() extension function of List returns true if all elements match the given predicate.
✐ Examples
1 Example
In this example,
- We create a list named
list1containing integers. - We use the
allextension function onlist1with a predicate that checks if each element is greater than0. - The
allfunction returnstrueif all elements satisfy the predicate; otherwise, it returnsfalse. - Finally, we print the value of
resultto standard output.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf(1, 2, 3, 4, 5)
val result = list1.all { it > 0 }
print(result)
}Output
true
2 Example
In this example,
- We create a list named
list2containing strings. - We use the
allextension function onlist2with a predicate that checks if the length of each string is greater than or equal to5. - The
allfunction returnstrueif all elements satisfy the predicate; otherwise, it returnsfalse. - Finally, we print the value of
resultto standard output.
Kotlin Program
fun main(args: Array<String>) {
val list2 = listOf("apple", "banana", "cherry")
val result = list2.all { it.length >= 5 }
print(result)
}Output
true
Summary
In this Kotlin tutorial, we learned about all() extension function of List: the syntax and few working examples with output and detailed explanation for each example.