Kotlin Array all()

Kotlin Array all()

In Kotlin, the all() function of Array class is used to check whether all elements in this array satisfy the given condition. It returns true if all elements match the specified condition, or false otherwise.

This function is useful when you want to verify that a certain condition is true for every element in the array.

In this tutorial, we’ll explore the syntax of the Array all() function and provide examples of its usage in Kotlin.

Syntax

The syntax of the all() function is:

fun <T> Array<out T>.all(predicate: (T) -> Boolean): Boolean

where

ParameterDescription
predicateA function that returns a Boolean value.
Parameters of Array.all() function

Examples for Array.all() function

1. Using all() to Check if given Array has all Positive Numbers

In this example, we’ll use all() to check if all numbers in the given array numbers are positive.

Kotlin Program

fun main() {
    val numbers = arrayOf(2, 4, 6, 8, 10)

    // Using all to check if all numbers are positive
    val allPositive = numbers.all { it > 0 }

    // Printing the result
    if (allPositive) {
        println("All numbers are positive.")
    } else {
        println("Not all numbers are positive.")
    }
}

Output

All numbers are positive.

Now, let us take a couple of negative numbers in the array, and run the program.

Kotlin Program

fun main() {
    val numbers = arrayOf(2, -10, 6, 8, 10, -5)

    // Using all to check if all numbers are positive
    val allPositive = numbers.all { it > 0 }

    // Printing the result
    if (allPositive) {
        println("All numbers are positive.")
    } else {
        println("Not all numbers are positive.")
    }
}

Output

Not all numbers are positive.

Summary

In this tutorial, we’ve covered the all() function in Kotlin arrays, its syntax, and how to use it to check whether all elements in an array satisfy a given condition.