Range Operator (..) in Kotlin


Definition

  • This operator is used to mention a range of values inclusive of the from and to values.
  • It is represented by ".."
  • This operator can be used only in the increasing order of ranges.
  • Range operators are mainly used along with in and !in operators.
  • While using range operator for iterating through a range, it is possible to set a range even skipping values. This is done using "step" keyword.

Syntax

1. Normal Usage

from_value .. to_value

For example,

if(4 in 1..10){
	//This will get printed while iterating through values : 1,2,3,4,5,6,7,8,9 and 10
	println("The value is in the range")
}

2. Range Operator with "step" Usage

from_value .. to_value step skip_value

For example,

if(4 in 1..10 step 4){
	//This will get printed while iterating through values 1,4 and 8 skipping 4 values starting from 1 until 10.
	println("The value is in the range")
}

Range Operator Example Program in Kotlin

//Range Operator Example Program in Kotlin
//Operator Kotlin Programs, Basic Kotlin Program
fun main(args: Array<String>) {
    println("Loop 1")
    //Printing values in range 100 to 105
    for(num in 100..105){
        println("$num is in the range")
    }

    println("\nLoop 2")
    //Printing values in range 100 to 105 skipping 2 values
    for(num in 100..105 step 2){
        println("$num is in the range")
    }
}

Sample Output

Loop 1
100 is in the range
101 is in the range
102 is in the range
103 is in the range
104 is in the range
105 is in the range

Loop 2
100 is in the range
102 is in the range
104 is in the range