Kotlin Array - any() Function



The Kotlin array any() function checks if an array has at least one element. It returns true if the array has an element. It also returns true if the array has at least one element matching with a specific predicate. Otherwise, it returns false.

An important use case of this function is to check whether an array contains an element based on the given predicate.

Syntax

Following is the syntax of Kotlin array any() function −

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

Parameters

This function accepts apredicateas a parameter, which is a lambda function that defines some condition.

Return value

This function returns a boolean value: true either an elements contains in the array or at-least one element satisfy the predicate; otherwise, false.

Example 1

Following is the basic example, we use the any() function to check an array contains at least one element or not −

fun main(args: Array<String>) {
   var array = Array(10) { i -> i}
   var result = array.any()
   if (result == true)
      println("The array is not empty")
   else
      println("The array is empty")
}

Output

Following is the output −

The array is not empty

Example 2

Now, let's see another example. Here, we use the any() function to check at least one element is available in the array according to the given predicate −

fun main(args: Array<String>) {
   var array = Array(10) { i ->
      if(i<3) {'c'}
      else if(i<5) {"Hi"}
      else {5}
   }
   var result = array.any() {
       i -> i is Int
   }
   if (result == true)
      println("A value in the array is of type integer")
   else
      println("None of values in the array is of type integer")
}

Output

Following is the output −

A value in the array is of type integer

Example 3

The example below displays the boolean value true if the array contains at least one element according to the given predicate; otherwise, false −

fun main(args: Array<String>) {
   val is_Even: (Int) -> Boolean = { it % 2 == 0 }
   val zero_To_Ten = 0..10
   
   println("zero_To_Ten.any { is_Even(it) } is ${zero_To_Ten.any { is_Even(it) }}")
   println("zero_To_Ten.any(isEven) is ${zero_To_Ten.any(is_Even)}") 
   
   val empty_List = emptyList<Int>()
   println("empty_List.any { true } is ${empty_List.any { true }}") 
}

Output

Following is the output −

zero_To_Ten.any { is_Even(it) } is true
zero_To_Ten.any(isEven) is true
empty_List.any { true } is false
kotlin_arrays.htm
Advertisements