In this guide, we will discuss the very cool feature of Kotlin which is ranges. With the help of ranges in Kotlin we can easily create a list of sequence by specifying starting and ending value. For example a range of 1..5 would create a series of values 1, 2, 3, 4, 5. Similarly we can create character ranges such as ‘A’..’D’ which will create a series of values A, B, C, D. We can also create ranges in reverse order and several other things with ranges. Lets get started.
A simple example of Kotlin Ranges
In the following example, we have created two ranges, one is an integer range and other one is a character range. We are cycling through the elements of the ranges using for loop.
/** * created by Chaitanya for Beginnersbook.com */ package beginnersbook fun main(args : Array<String>){ println("Number range:") for(num in 1..4){ println(num) } println("Character range:") for(ch in 'A'..'E'){ println(ch) } }
Output:
Check element in Ranges
We can also check whether a particular element is present in the range or not. Lets see how to do this with the help of a simple example.
package beginnersbook fun main(args : Array<String>){ val oneToTen = 1..10 println("3 in oneToTen: ${3 in oneToTen}") println("11 in oneToTen: ${11 in oneToTen}") }
Output:
3 in oneToTen: true 11 in oneToTen: false
Kotlin Range: rangeTo() and downTo() functions
Instead of .. we can use these functions rangeTo() and downTo(), rangeTo() is for increasing order and downTo() is for decreasing order.
/** * created by Chaitanya for Beginnersbook.com */ package beginnersbook fun main(args : Array<String>){ val oneToFive = 1.rangeTo(5) val sixToThree = 6.downTo(3) println("rangeTo:") for(x in oneToFive){ println(x) } println("downTo") for(n in sixToThree){ println(n) } }
Output:
Kotlin Range Step
With the help of step() function we can define the interval between the values. By default the value of step is 1 so when we create range 1..10, it is 1, 2, 3,..10. However if we want a specific interval like 3 then we can define the range like this 1..10.step(3) this way the values would be 1 4 7 10. Lets take an example.
package beginnersbook fun main(args : Array<String>){ val oneToTen = 1..10 val odd = oneToTen.step(2) for(n in odd){ println(n) } }
Output:
1 3 5 7 9
Kotlin range reverse
We can reverse a range in Kotlin using reversed() function.
/** * created by Chaitanya for Beginnersbook.com */ package beginnersbook fun main(args : Array<String>){ val oneToFive = 1..5 for (n in oneToFive.reversed()){ println(n) } }
Output:
Leave a Reply