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
1..n
但这是一个inclusive
范围,包括1
和n
.如何创建exclusive
个范围.
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
1..n
但这是一个inclusive
范围,包括1
和n
.如何创建exclusive
个范围.
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 +1) to (upper bound - 1).
fun Int.exclusiveRangeTo(other: Int): IntRange = IntRange(this + 1, 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.