Kotlin List any()
Syntax & Examples


Syntax of List.any()

There are 2 variations for the syntax of List.any() extension function. They are:

1.
fun <T> Iterable<T>.any(): Boolean

This extension function returns true if collection has at least one element.

2.
fun <T> Iterable<T>.any(predicate: (T) -> Boolean): Boolean

This extension function returns true if at least one element matches the given predicate.



✐ Examples

1 Example

In this example,

  • We create a list containing integers from 1 to 5.
  • We use the 'any' function without a predicate to check if the list has at least one element.
  • Since the list has elements, the 'any' function returns true.
  • We print the result, which is true.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(1, 2, 3, 4, 5)
    val result = list.any()
    println(result) // Output: true
}

Output

true

2 Example

In this example,

  • We create a list containing integers from 1 to 5.
  • We use the 'any' function with a predicate that checks if any element is greater than 3.
  • Since the list contains elements greater than 3 (4 and 5), the 'any' function returns true.
  • We print the result, which is true.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(1, 2, 3, 4, 5)
    val result = list.any { it > 3 }
    println(result) // Output: true
}

Output

true

3 Example

In this example,

  • We create a list containing integers from 1 to 5.
  • We use the 'any' function with a predicate that checks if any element is greater than 10.
  • Since none of the elements in the list are greater than 10, the 'any' function returns false.
  • We print the result, which is false.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(1, 2, 3, 4, 5)
    val result = list.any { it > 10 }
    println(result) // Output: false
}

Output

false

Summary

In this Kotlin tutorial, we learned about any() extension function of List: the syntax and few working examples with output and detailed explanation for each example.