Creating exclusive ranges in kotlin

You can use the until function in the Kotlin stdlib:

for (i in 1 until 5) {
    println(i)
}

Which will print:

1
2
3
4

Update 2022: Please use the built-in function until.


Old answer:

Not sure if this is the best way to do it but you can define an Int extension which creates an IntRange from (lower bound) to (upper bound - 1).

fun Int.exclusiveRangeTo(other: Int): IntRange = IntRange(this, other - 1)

And then use it in this way:

for (i in 1 exclusiveRangeTo n) { //... }

Here you can find more details about how ranges work.

Tags:

Range

Kotlin