Kotlin Range
11. Kotlin Range
11.1 Range Operators
11.2 Range Utility Functions
Range operators
In Kotlin, the range is a sequence between the given start value and end value. It consists of a start, a stop, and the step. The value of step is by default 1 and the start and stop are inclusive in the Range. The (..) operator is used to create a range expression which is complemented by in and !in.
Example of Kotlin range
fun main(args : Array<String>) {
for(i in 1..10) {
println(i)
}
}
Output
1
2
3
4
5
6
7
8
9
10
Kotlin in operator
The in operator is used to check whether a number is within the range.
Example
fun main(args : Array<String>) {
val x = 3
val y = 10
if (x in 1..y) {
println("x is in range")
}
}
Output
3 is in range
Kotlin !in operator
The !in operator is used to check whether a number is not within the range.
Example
fun main(args : Array<String>) {
val x = 12
val y = 10
if (x !in 1..y) {
println("x is not in range")
}
}
Output
12 is not in range
Kotlin Range Iteration
We can easily used loop operators to iterate over a range.
Example
fun main(args : Array<String>) {
for (x in 1..10) {
println("$x")
}
}
Output
1
2
3
4
5
6
7
8
9
10
Range Utility Functions
Kotlin rangeTo() function
The rangeTo() function is itegral type which calls the constructor of Range class. The function is used to return the value from the start to end as mentioned in the range in increasing order.
fun main(args : Array<String>) {
for (i in 1.rangeTo(10))
println("$i")
}
Output
1
2
3
4
5
6
7
8
9
10
Kotlin downTo() function
The downTo() function is used to return the value in decreasing order.
fun main(args : Array<String>) {
for (x in 'h' downTo 'a')
println("$x")
}
Output
h
g
f
e
d
c
b
a
Kotlin reversed() function
The reversed() function is used to return the reverse order of the given range.
fun main(args : Array<String>) {
for (x in 1..5)
print("$x")
}
Output
1
2
3
4
5
Kotlin step() function
The step() function is used to return the range value in interval of given step value. The step value is required to be always positive, therefore this function never changes the direction of iteration.
fun main(args : Array<String>) {
for (x in 1..10 step 5)
print("$x")
}
Output
1
6