51

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

1..n

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

Mahozad
  • 18,032
  • 13
  • 118
  • 133
Chetan Kothari
  • 761
  • 1
  • 5
  • 12

4 Answers4

110

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
Nycto
  • 1,670
  • 2
  • 14
  • 18
  • Note: In Kotlin 1.1, using "until" with integers does not generate the same optimized code as writing: for (i in 1..n-1) {...} – BladeCoder Jun 12 '17 at 18:11
  • @BladeCoder is this still true for Kotlin 1.2? – leonardkraemer Dec 14 '17 at 00:00
  • 4
    @leoderprofi Yes things have changed. "until" is now optimized since Kotlin 1.1.4 – BladeCoder Dec 18 '17 at 20:46
  • 7
    This works for the the case when the last number in the range is excluded, but what about when we want to exclude the first number? – Rylander Aug 15 '18 at 23:58
  • @MikeRylander I suppose you start the loop with the indexer already having the desired value. Usually we want indexer to be one off to use a collection count to fetch indexed arrays, right? – cbaldan Jun 21 '21 at 18:57
13

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.

rciovati
  • 27,603
  • 6
  • 82
  • 101
2

With Kotlin 1.8 and newer use the new ..< (rangeUntil) operator:

@OptIn(ExperimentalStdlibApi::class)
fun exampleFunction() {
    for (i in 1 ..< 5) {
        println(i) // 1, 2, 3, 4
    }
}

It also opens possibilities that could not be done with until:

val floatRange = 0f ..< 1f
val dateRange = LocalDate.of(2022, 1, 1) ..< LocalDate.of(2023, 1, 1)
val stringRange = "1z" ..< "9a"
// OR anything implementing Comparable

See official Kotlin video introducing the rangeUntil operator.

Mahozad
  • 18,032
  • 13
  • 118
  • 133
0

The most backward compatible way is to use kotlin's until operator. E.g.

for (val i in 0 until 5){
   /*do stuff*/
}