liveBook · Manning

Interval

As explained in Kotlin in Action, 2E

An interval is a connected set or span of values between specified lower and upper endpoints, with endpoint inclusion determined by its definition.

An interval is a connected set of values between endpoints. In Kotlin, the `..` operator creates an inclusive range, such as `1..10`, replacing many traditional counter-based `for` loops. section 2.4.2 section 2.6

Iterate through an interval

```kotlin fun main() { for (i in 1..100) { print(fizzBuzz(i)) } } ``` Here, `1..100` supplies each integer from 1 through 100. A progression can change traversal with `downTo` and `step`: `100 downTo 1 step 2` visits descending even numbers.

Use intervals for traversal, membership tests, and comparable values:

  • Use `in` and `!in` to test whether a value belongs to an interval, including character checks such as `c in 'a'..'z'`. section 2.4.4
  • Create ranges from comparable objects, including dates; `..<` excludes the upper endpoint. section 9.3.3

The `..` operator is shorthand for `rangeTo`. Kotlin’s standard library supports it for comparable elements, while enumerable progressions apply when values can be stepped through, such as numbers and characters. Parenthesize a range before calling a method on it, as in `(0..n).forEach { ... }`. section 9.3.3

How Kotlin in Action, 2E covers it

How deep it goes
Explains inclusive and open-end ranges, stepped progressions, membership, Comparable values, and the rangeTo convention.
Examples
Uses Fizz-Buzz, descending even-number iteration, character classification, string membership, and date intervals.
What it assumes
Assumes basic Kotlin loops and expressions while introducing ranges as an alternative to classical counter-based loops.
What you can do after
Apply it via Kotlin syntax to iterate, step through, classify, and test membership among ordered values.
How it connects
Connects ranges with progressions, for loops, when expressions, membership operators, Comparable, extension functions, and Java LocalDate.

Also explained in

Compare how 7 books explain interval →

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.