liveBook · Manning

Membership operator

As explained in Kotlin in Action, 2E

The `in` operator tests whether a value belongs to a collection, range, or other container by invoking its containment operation.

The `in` operator checks whether a value belongs to a range or collection; `!in` checks that it does not. The same syntax also supports iteration, while membership checks make validation and classification concise. section 2.4.4 section 2.6

Check characters with ranges

fun isLetter(c: Char) = c in 'a'..'z' || c in 'A'..'Z' fun isNotDigit(c: Char) = c !in '0'..'9' println(isLetter('q')) // true println(isNotDigit('x')) // true The range hides the underlying comparison between character codes. Membership checks can also appear directly in `when` branches, such as `in '0'..'9'` for digit recognition.

Membership works across several kinds of containers and ranges:

  • Use comparable objects in ranges: `"Kotlin" in "Java".."Scala"` is true because strings are compared alphabetically. section 2.4.4
  • Use open ranges such as `10..<20` when the ending value should be excluded; closed ranges such as `10..20` include both endpoints. section 9.3.2

Kotlin implements membership through an operator convention. In `element in container`, the right-hand object receives a `contains(element)` call. A class can therefore define its own membership behavior with an `operator fun contains(...)` function. section 9.3.2 section 9.3

How Kotlin in Action, 2E covers it

How deep it goes
Explains range and collection checks, comparable ranges, open endpoints, and the `contains` convention for custom classes.
Examples
Demonstrates character predicates, `when` branches, string and set membership, and rectangle containment.
What you can do after
Apply it via Kotlin syntax to test ranges and collections or implement `contains` for custom containment behavior.
How it connects
Connects membership with ranges, collections, Comparable, `when` expressions, operator overloading, and custom containment.

Also explained in

Compare how 8 books explain membership operator →

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.