Kotlin Tutorial Beginner Guide for Kotlin Programming Language Tutorial

Ranges in Kotlin

The Range is a special type of Kotlin Programming Language. In Kotlin Range we need to define Start and an End Value. The Range contains value based on Start and the End Values. The Range in Kotlin Programming Langauge is closed, it means in Range include Start and End value. For defining Range we need to use double dots “..”. Following are the example of Ranges.

//Start 1 End 12
val monthOfYear = 1..12
//Start 1 End 6
val oneToSix = 1..6
//Start a End z
val aToZ = "a".."z"

Now where we can use it. One is to check value in a Range. For example, we get an input for the month from the user, then we can check if the value is a valid month or not using monthOfYear.


in Operator

To check a value is in Range use “in” operator. Following are some example

val isValidMonth = 4 in monthOfYear
val isValidAlphabet = "f" in aToZ

Some special Range library functions

rangeTo() Function

rangeTo() function is similar to “..” double dots operator. In the above example, we define a range “oneToSix”. We can also define it using rangeTo() function.

val oneToSix = 1.rangeTo(6)

downTo() Function

downTo() function is revere of rangeTo() function. Following is the example for downTo() function

val sixToOne = 6.downTo(1)

Note: Please try to use val sixToOne = 6..1 and share your learning with use using comment section.

Once our ranges are created we can modify our ranges using following functions

step() Function

It is used to modify the delta between each successive term in range. Following are the example, for step() function

val oneToTen = 1.rangeTo(10)
val tenToOne = 10.downTo(1)

val step2 = oneToTen.step(2)
val step3 = oneToTen.step(3)
val rStep2 = tenToOne.step(2)
val rStep3 = tenToOne.step(3)

Comments are the values inside the specific range.

reversed() Function

It is used to reverse the specific range.

val oneToTen = 1.rangeTo(10)
val oneToTenReversed = oneToTen.reversed()

This is all about Ranges in Kotlin Programming Language. In this chapeter we used Range but we are not able to check it’s contents for this we are going to use Loops and It is our next topic to learn.

Leave A Comment

Please login to post your valuable comments.