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
but this is an inclusive
range which includes 1
and n
. How do I create exclusive
ranges.
A Kotlin range is created with the .. operator or with the rangeTo and downTo functions. Kotlin ranges are inclusive by default; that is, 1.. 3 creates a range of 1, 2, 3 values.
To create a range for your class, call the rangeTo() function on the range start value and provide the end value as an argument. rangeTo() is often called in its operator form .. .
Returns a progression from this value down to the specified to value with the step -1. The to value should be less than or equal to this value. If the to value is greater than this value the returned progression is empty.
Kotlin range is defined as an interval from start value to the end value. Range expressions are created with operator (. .) which is complemented by in and !in. The value which is equal or greater than start value and smaller or equal to end value comes inside the definedrange.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With