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): Boolean
This 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
list1
containing integers. - We use the
all
extension function onlist1
with a predicate that checks if each element is greater than0
. - The
all
function returnstrue
if all elements satisfy the predicate; otherwise, it returnsfalse
. - Finally, we print the value of
result
to 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
list2
containing strings. - We use the
all
extension function onlist2
with a predicate that checks if the length of each string is greater than or equal to5
. - The
all
function returnstrue
if all elements satisfy the predicate; otherwise, it returnsfalse
. - Finally, we print the value of
result
to 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.