Kotlin Array any()

Kotlin Array any()

In Kotlin, the any() function of Array class is used to check whether at least one element in this array satisfies the given condition. It returns true if at least one element matches the specified condition, or false otherwise.

This function is useful when you want to determine if there’s at least one element in the array that meets a particular criterion.

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

Syntax

The syntax of the any() function is:

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

where

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

Examples for Array.any() function

1. Using any() to Check if given Array has Even Numbers

In this example, we’ll use any() to check if there’s at least one even number in the given array numbers.

Kotlin Program

fun main() {
    val numbers = arrayOf(1, 3, 5, 7, 8)
    
    // Using any to check for even numbers
    val hasEvenNumber = numbers.any { it % 2 == 0 }
    
    // Printing the result
    if (hasEvenNumber) {
        println("The array contains at least one even number.")
    } else {
        println("The array does not contain any even numbers.")
    }
}

Output

The array contains at least one even number.

Now, let us take numbers in the array that there are no even numbers.

Kotlin Program

fun main() {
    val numbers = arrayOf(1, 3, 5, 7)
    
    // Using any to check for even numbers
    val hasEvenNumber = numbers.any { it % 2 == 0 }
    
    // Printing the result
    if (hasEvenNumber) {
        println("The array contains at least one even number.")
    } else {
        println("The array does not contain any even numbers.")
    }
}

Output

The array does not contain any even numbers.

Summary

In this tutorial, we’ve covered the any() function in Kotlin arrays, its syntax, and how to use it to check whether at least one element in an array satisfies a given condition.