Ranges

Ranges

Range expressions are formed with rangeto function  that have the operator form ..(Double dot operator), range is defined for any comparable type.

var intRange=1..5//this range contains 1,2,3,4,5

var intDownRange= 5 downTo  1//this range contains 5,4,3,2,1
var stringRange="a".."z"//this range contains a,b,c...z

var charRange='a'..'z' 
//this range contains a,b,c...z
var downRange=5 downTo 1 step 2//this range contains 5,3,1
var upRange = 1..5 step 2//this range contains 1,3,5

var charIncRange='a'..'z' step 2//this range contains a,c,e...z

Ranges are mostly used in loops.
The step key keyword is used  for arbitrary loops

fun main(args:Array<String>)
{
for (i in intDownRange)
{
    print(i)
}
}

Output
54321

To create a range which does not include its end element, You can use the until function
fun main(args:Array<String>)
{
for (i in 1 until 10) { // i in [1, 10), 10 is excluded    print(i)
}
}

Output
123456789



Ranges implements a common interface in the library :ClosedRange<T>

Comments