Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 134 ยท Control Flow

Ranges and Progressions

Understand Kotlin ranges and progressions - IntRange, CharRange, in checks, rangeUntil, reversed, step, floating-point ranges, custom ranges and the pitfalls, with runnable examples.

You already used ranges in Loops: 1..5, 0 until n, 10 downTo 1. They look like special syntax, but a range is an ordinary object, with a type, properties and functions. Understanding what that object is explains several behaviors that otherwise seem arbitrary: why 5..1 is empty, why step returns a different type, why 1.0..2.0 cannot be looped over, and why in checks on a range are so cheap.

This lesson gives you the full picture: ranges (a start and an end), progressions (a start, an end and a step), ranges of characters, floating-point and custom ranges, and the practical tools for everyday code: membership tests, reversed, coerceIn, and slicing lists and strings.

A range is an object

The .. operator is shorthand for a function called rangeTo. 1..5 is the same as 1.rangeTo(5), and the result is an IntRange, a small object that stores only the first and last values. It does not store the numbers in between, so 1..1_000_000_000 costs just as little memory as 1..3.

Kotlin Inspecting a range

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The numbers only come into existence when something iterates over the range, for example toList(), a for loop or sum(). Even so, a for loop over a literal range such as for (i in 1..n) is compiled into a plain counting loop, so no IntRange is allocated at all.

Ranges exist for the integer types (IntRange, LongRange) and for Char (CharRange). Each of these is also a progression: a sequence with a first element, a last element and a constant step. A range is simply a progression whose step is 1.

Membership: the in operator

The most common use of a range is not looping but asking "is this value inside?" The in operator does that, and !in negates it.

Kotlin in and !in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

score in 50..100 is exactly score >= 50 && score <= 100, and for an integer range the compiler generates precisely that comparison. It does not build a range object first. It is easier to read and harder to get wrong than two comparisons, and it works as a branch condition in when (see when Expressions).

Excluding the end: until and rangeUntil

The .. range includes both ends. When you want to exclude the end, as with indexes 0 to size - 1, you have two spellings: until and the operator ..<.

Kotlin Closed and half-open ranges

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

a..<b calls the function rangeUntil. All three forms produce an IntRange; 1 until 5 and 1..<5 are even the same range as 1..4. Prefer ..< in new code: you can see at a glance that it is a range operator, while until is an infix function that is easier to mistake for English. Both are fine and both appear in the wild.

Direction and step: progressions

downTo and step produce an IntProgression (and LongProgression, CharProgression). Like a range, it knows its first, last and step.

Kotlin Progressions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Two details deserve attention. First, a progression's last is the last element it actually produces, not the number you wrote: 1..10 step 4 produces 1, 5, 9, so last is 9. Second, reversed() on a progression flips it, step included, so the reversed version of 1..10 step 4 is 9, 5, 1, and not 10, 6, 2.

Because step must be positive, step 0 and negative steps throw an exception. The exception is raised when you build the progression:

Kotlin A step of zero (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The run ends with Exception in thread "main" java.lang.IllegalArgumentException: Step must be positive, was: 0. Validate user-supplied steps before you use them.

Character ranges

'a'..'e' is a CharRange. It follows the character codes, so it works for any sequence of consecutive characters in Unicode, which includes the lowercase letters, the uppercase letters and the digits.

Kotlin CharRange

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The condition it in '0'..'9' is the standard way to test a digit, although for real text you would use it.isDigit(), which also handles digits from other scripts (see Strings).

Ranges over any Comparable type

The .. operator works on any type that implements Comparable. If the type is not a primitive number or Char, you get a general ClosedRange<T>. It supports the in test, but it has no iteration, because Kotlin cannot know what "the next value" is.

Kotlin Floating-point, String and date ranges

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Strings compare alphabetically, so "banana" in "apple".."cherry" is true. Also notice 0.5 in 0.0..1.0: the range contains every real number between 0.0 and 1.0, not just the ones you could count. Because there is no next element, you cannot loop over it:

Kotlin Looping over a Double range (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler stops with main.kt:2:15: error: for-loop range must have an 'iterator()' method. The iterator() function is what for needs. If you need a sequence of doubles, build it from integers, or from generateSequence: (0..4).map { it * 0.25 } gives 0.0, 0.25, 0.5, 0.75, 1.0. Writing the calculation from an integer index also avoids the rounding errors that repeated addition of 0.1 would collect.

Open-ended ranges

With ..< the end is excluded, which gives an OpenEndRange<T> for the general case. This is useful for half-open intervals of doubles or dates, such as the ranges of a pricing table where each band starts exactly where the last one ended:

Kotlin Half-open ranges avoid gaps and overlaps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

If you used 0.0..1.0 and 1.0..5.0, a parcel of exactly 1.0 kg would match the first branch, and the second range would overlap it. Half-open ranges make each boundary belong to exactly one band.

Handy functions around ranges

A few tools you will use constantly:

  • coerceIn(min, max) forces a value into a range; coerceAtLeast and coerceAtMost limit one side.
  • random() picks a random element from an integer range.
  • list.slice(1..3) and string.substring(1..3) take parts by index range.
  • isEmpty() tells you whether a range has no elements.
Kotlin coerceIn, slice and substring with ranges

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

substring(2..5) is inclusive of index 5, unlike the two-argument substring(2, 5) which excludes the end index. Mixing the two conventions is a common source of off-by-one errors, so check which form you are using. The index ranges substring(a..b) and slice(a..b) throw IndexOutOfBoundsException when b is past the end.

Your own ranges

Any class that implements Comparable<T> gets .. for free, because the standard library defines operator fun <T : Comparable<T>> T.rangeTo(that: T): ClosedRange<T>. To make your own type iterable in a for loop, you provide an iterator() function, as shown in Operator Conventions. For most code a ClosedRange that supports in is all you need:

Kotlin A Comparable class with a range

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Pitfalls

  • Reversed ranges are empty. 10..1 iterates zero times. Use 10 downTo 1.
  • step after .. binds loosely. 0..10 step 2 works as expected, but 1 + 1..5 parses as (1 + 1)..5, because .. has lower precedence than +. When in doubt add parentheses.
  • Int overflow at the edges. Int.MAX_VALUE - 1..Int.MAX_VALUE is fine, because Kotlin's progressions are designed not to overflow when the last element is Int.MAX_VALUE.
  • A range of doubles is not a list. There is no toList() and no for.
  • in on a list is not a range check. 5 in listOf(1, 5, 9) searches the list element by element; 5 in 1..9 is two comparisons. Choose a range when the values form an interval.

When you read the name of a type in an error message, IntProgression means "an integer sequence with a step", IntRange means "step is 1", and ClosedRange<T> means "only comparisons, no iteration".

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does (1 until 5).toList() produce?

    until excludes the end value, so 1 until 5 yields 1, 2, 3, 4. The same applies to 1..<5.
  2. 2. What is (1..10 step 4).last?

    The progression produces 1, 5 and 9. Its last property is the last element it really produces, which is 9.
  3. 3. Why does for (x in 0.0..1.0) not compile?

    A range of doubles supports membership tests (in) but cannot be iterated. Use integers and multiply, or a sequence.
  4. 4. What does "adventure".substring(2..5) return?

    substring with an IntRange includes the end index, so indexes 2 to 5 give four characters. The Int, Int overload would exclude the end.
  5. 5. Which condition is equivalent to x in 10..20?

    A closed range includes both ends, so the check is x >= 10 && x <= 20.

Summary

  • a..b is the function rangeTo and creates a small object (IntRange, LongRange, CharRange, or ClosedRange<T>), not a list.
  • in and !in test membership; for numbers they compile to plain comparisons.
  • until and ..< exclude the end; downTo counts down; step makes a progression with a positive step; reversed() flips a progression.
  • A range from the larger to the smaller number is empty.
  • Any Comparable type, such as Double, String or LocalDate, supports .. and in, but only integer-like ranges can be iterated.
  • coerceIn, slice and substring(range) are the everyday helpers; remember substring(range) includes the end index.

Next: Null Safety