Creating exclusive ranges in kotlin


I am just starting with Kotlin. I want to create range from 1 to n where n is excluded. I found out that Kotlin has ranges and I can use them as follows


but this is an inclusive range which includes 1 and n. How do I create exclusive ranges.


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.

Answered By – rciovati

Answer Checked By – Dawn Plyler (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.