Kotlin - Data Type Ranges

Introduction

A range is an interval that has a start value and an end value.

Any types comparable can be used to create a range, which is done using the .. operator:

Demo

fun main(args: Array<String>) {
        val aToZ = "a".."z" 
        val oneToNine = 1..9 
        //from  w w  w .  ja  v a  2s .  c o  m
        println(aToZ)
        println(oneToNine)
}

Once a range is created, the in operator can be used to test whether a given value is included in the range.

For a value to be included in a range, it must be greater than or equal to the start value and less than or equal to the end value:

Demo

fun main(args: Array<String>) {

        val aToZ = "a".."z" 
        val isTrue = "c" in aToZ 
        val oneToNine = 1..9 
        val isFalse = 11 in oneToNine 

        println(oneToNine)//from ww  w  .  j  ava 2  s . c  o  m
        println(isFalse)
        
}

Integer ranges (ints, longs, and chars) can be used in a for loop.

There are functions to create ranges not covered by the .. operator,

For example, downTo() will create a range counting down and rangeTo() will create a range up to a value.

Both of these functions are defined as extension functions on numerical types:

Demo

fun main(args: Array<String>) {
        val countingDown = 100.downTo(0) 
        val rangeTo = 10.rangeTo(20) 
        //  w w w. jav  a  2s .c  om
        println(countingDown)
        println(rangeTo)
}

Once a range is created, you can modify the range, returning a new range.

To modify the delta between each successive term in the range, we can use the step() function:

Demo

fun main(args: Array<String>) {

        val oneToFifty = 1..50 
        val oddNumbers = oneToFifty.step(2) 
        // w  w  w . jav a2s . com
        println(oneToFifty)
        println(oddNumbers)

}

You cannot use a negative value here to create a decreasing range.

Ranges can be reversed using the reversed() function.

It returns a new range with the start and end values switched, and the step value negated:

Demo

fun main(args: Array<String>) {

        val countingDownEvenNumbers = (2..100).step(2).reversed() 
        /*from   w w w. j  a v  a 2  s.c  om*/
        println(countingDownEvenNumbers)

}