Kotlin List.all() – Examples

Kotlin List.all()

The Kotlin List.all() function returns true if all elements match the given predicate. Else, the function returns false.

Syntax

List.all(predicate)

Example 1

In this example,

  1. Take a list of numbers.
  2. Define a predicate that the number should be even.
  3. Call List.all() with predicate passed as argument.
  4. If all the elements of list matches the predicate, we should get true as return value from all().

Program

fun main(args: Array<String>) {
    val list1 = listOf(4, 22, 8, 20)
    val predicate: (Int) -> Boolean = {it % 2 == 0}
    val result = list1.all(predicate)
    print(result)
}

Output

true

Example 2

In this example,

  1. Take a list of numbers.
  2. Define a predicate that the number should be even.
  3. Call List.all() with predicate passed as argument.
  4. If any of the elements of list does not match the predicate, we should get false as return value from all().

Program

fun main(args: Array<String>) {
    val list1 = listOf(4, 3, 8, 20)
    val predicate: (Int) -> Boolean = {it % 2 == 0}
    val result = list1.all(predicate)
    print(result)
}

Output

false