liveBook · Manning

Any

As explained in Kotlin in Action, 2E

any is a Kotlin standard-library operation that returns true when at least one element in a collection satisfies a predicate.

Kotlin’s any operation answers a practical collection question: does at least one element satisfy this predicate? It returns a Boolean and expresses the intent directly, without manually looping or counting matches. section 6.1.3

Check whether someone qualifies

val canBeInClub27 = { p: Person -> p.age <= 27 } val people = listOf(Person("Alice", 27), Person("Bob", 31)) println(people.any(canBeInClub27)) // true The lambda defines the condition; any applies it to the collection and succeeds because Alice matches. The predicate can also be written inline: people.any { it.age <= 27 }. section 6.1.3

Choose the predicate operation that matches the question:

  • Use any when at least one element must match. section 6.1.3
  • Replace !all with any and a negated predicate when that wording is clearer: !list.all { it == 3 } becomes list.any { it != 3 }. section 6.1.3
  • Replace !any with none when the question is whether no elements match. section 6.1.3
  • Remember that any returns false for an empty collection because no element can satisfy the predicate. section 6.1.3
  • Use count when you need the number of matching elements, or find when you need the first matching element. section 6.1.3

Predicates are Boolean-returning lambdas, so the same style applies across collections and sequences. Prefer any over a negated all or a manual search when it makes the requirement easier to read and maintain. section 6.3 section 6.1.3

How Kotlin in Action, 2E covers it

How deep it goes
Explains predicate use, logical equivalents, sibling operations, and empty-collection behavior without descending into implementation internals.
Examples
Uses an age predicate over people, integer comparisons, negated all and any, and an empty list.
What it assumes
Assumes familiarity with collections and lambdas while demonstrating predicates from simple collection examples.
What you can do after
Apply it via the Kotlin standard library to express readable existence checks over collections and sequences.
How it connects
Connects any with predicates, lambda functions, all, none, count, find, collections, and sequences.

Also explained in

Compare how 2 books explain any →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.