Kotlin Range

11. Kotlin Range 11.1 Range operators 11.2 Range Utility Functions


Range operators

Kotlin range is a sequence between the given start value and end value. The (..) operator is used to create a range expression which is complemented by in and !in.

Example

fun main(args : Array<String>)  { 
	for(i in 1..10) {
		println(i)
	}
}
Output
1
2
3
4
5
6
7
8
9
10

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




!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

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

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

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

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

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







Read more articles


General Knowledge



Learn Popular Language