liveBook · Manning

Predicate

As explained in Kotlin in Action, 2E

A predicate function is a function that evaluates an input and returns a Boolean indicating whether it satisfies a condition.

A predicate is a function that evaluates an input and returns Boolean: true when the input satisfies a condition and false otherwise. Kotlin uses predicates extensively with collection operations such as filter, all, any, none, count, and find. section 6.1.3 section 6.3

Defining and applying a predicate

val canBeInClub27 = { p: Person -> p.age <= 27 } val people = listOf(Person("Alice", 27), Person("Bob", 31)) println(people.any(canBeInClub27)) // true println(people.count(canBeInClub27)) // 1 println(people.find(canBeInClub27)) // Person(name=Alice, age=27) The lambda accepts a Person and returns a Boolean. Collection functions call it for each element, then use the result for their specific job. section 6.1.3

Choose the collection operation whose name matches the question:

  • all checks whether every element satisfies the predicate. section 6.1.3
  • any checks whether at least one element satisfies it; none checks whether no element satisfies it. section 6.1.3
  • count returns the number of matching elements, while find returns the first matching element. section 6.1.3
  • For readability, prefer any with a negated condition over !all, and none over !any. section 6.1.3
  • On an empty collection, any returns false, none returns true, and all returns true. section 6.1.3

Predicates are function values, so higher-order functions can accept them as parameters or return them. A filter implementation calls predicate(char) for each character and keeps only characters for which the result is true. A UI filter can likewise construct a predicate from prefix and phone-number settings, separating filtering policy from display logic. section 10.1.2 section 10.1.5

val canBeInClub27 = { p: Person -> p.age <= 27 }

Inspect the compact Kotlin predicate definition used to query people by age. section 6.1.3

How Kotlin in Action, 2E covers it

How deep it goes
Explains predicate syntax, collection behavior, higher-order implementation, negation choices, and empty-collection edge cases.
Examples
Demonstrates age checks, collection queries, character filtering, empty collections, and configurable contact-list filtering.
What it assumes
Assumes basic Kotlin lambdas and collections, then develops function types through concrete filtering examples.
What you can do after
Apply predicates via Kotlin collection functions and implement higher-order functions that accept or return filtering logic.
How it connects
Connects predicates with lambdas, higher-order functions, collection operations, sequences, and filtering.

Also explained in

Compare how 5 books explain predicate →

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.