Range and Iteration

Imagine telling someone to count from one to five by uttering “set i equal to 1 but while keeping i less than 6, increment i and report the value.” If we had to communicate with a fellow human that way, it would have ended civilization a long time ago. Yet that’s how programmers have been writing code in many C-like languages. But we don’t have to, at least not in Kotlin.

Range classes

Kotlin raises the level of abstraction to iterate over a range of values with specialized classes. For instance, here’s a way to create a range of numbers from 1 to 5.

// ranges.kts
val oneToFive: IntRange = 1..5

The type IntRange, which is part of the kotlin.ranges package, is provided for clarity, but you may leave it out and let type inference figure out the variable’s type.

If you want a range of letters in the English alphabet, the process is the same:

// ranges.kts
val aToE: CharRange = 'a'..'e'

You’re not limited to primitives like int, long, and char. Here’s a range of strings:

// ranges.kts
val seekHelp: ClosedRange<String> = "hell".."help"

That’s nifty. Take the initial value, place the .. operator, followed by the last value in the range. The range includes both the values before and after the .. operator. Let’s quickly check if a couple of values exist in that range.

Get hands-on with 1400+ tech skills courses.