
1. Overview
In this article, we will focus on the Kotlin range exclusive.
2. Kotlin range
First, let’s have a unified understanding of the Kotlin Range. A range is an interval that defines a range of values from the specified start to the end value. It includes both the start and end values in the range specified.
The start of the range is always is less than or equal to the end of the range. The syntax of Kotlin range is:
start..end
In the below code, the range is 1 to 4. 1 is the start value and 4 is the end value. The range includes both 1 and 4.
1..4
Let’s take another example for Range.
In the below code, the value of foo
is 5. The following if statement
evaluates whether the foo
value is in the range 1 to 5. Since both the values 1 and 5 are inclusive, the if condition passes and prints 5.
fun main() { val foo = 5 if (foo in 1..5) { print(foo) } }
3. Kotlin range inclusive
As mentioned earlier, the Kotlin range is inclusive, meaning it includes both the start and end of the range. For example, the below for loop prints from 1 to 5.
fun main() { for (i in 1..5) { print(i) } }
Now, let’s see how you can exclude start or end from the range.
4. Kotlin range exclusive
There might be scenarios where you want the end
or start
to be excluded. To achieve this, you can follow any of the below approaches as an alternative to the range.
Assume you had to create a range from 1
to n
where n
excluded
. Then, you can use the until
function to exclude the end value.
The below code excludes the end value 5 and so print only from 1 to 4.
fun main() { for (i in 1 until 5) { print(i) } }
Alternatively, you can create an extension function to the IntRange and handle it. You can exclude both start and end using the extension function.
fun Int.rangeExcludeEnd(other: Int): IntRange = IntRange(this, other - 1) fun Int.rangeExclude(other: Int): IntRange = IntRange(this+1, other - 1) fun Int.rangeStartExclusive(other: Int): IntRange = IntRange(this+1, other)
5. Conclusion
In this article, we have seen the Kotlin range exclusive with examples.