Ranges

A range is a sequence of values between defined lower and upper limits.

The ClosedRange interface represents a range of values.

Integral type ranges, i.e. CharRange, IntRange, LongRange have an extra feature: they can be iterated over. It means range can be used in for loop and has stream methods such as filter().

The .. operator creates range from first value to second value inclusive. Also you can use the rangeTo() and downTo() functions.

The step function defines a distance between two values. By default it is 1.

Method contains() can be used as operator in.

val rangeInt = 1..20 // [1..20]
val rangeIntExclusive = 1 until 20 // [1..20)
val rangeCh = 'o' downTo 'a' // ['o'..'a'], reverse order with step 1

val start = Date("2017-01-01")
val end = Date("2017-12-31")
val range = start..end

rangeCh.forEach{
    print("$it ")
}

for (ch in 'o' downTo 'a')
    print("$ch ")

if(ch in rangeCh){
    // do something
}

if(ch !in rangeCh){
    // do something
}

val it = rangeCh.iterator()
while (it.hasNext()) {
    val v = it.next()
    println(v)
}

println((1..20 step 2).last)
println((1..20 step 3).first)
println((1..20 step 4).step)

for (i in 1..20 step 5) {
    print("$i ")
}