Using Kotlin Range Expressions

In this article’ we will learn about kotlin range expressions. Kotlin range expressions can be useful when it comes to working with flow control statements.

Step 1

Let’s create a variable and assign to it a random integer value:

val randomInt = Random().nextInt()

Now we can check whether the randomInt value belongs to the scope of integers from 0 to 10 inclusive using range expressions:

if (randomInt in 0..10) {
    print("$randomInt belongs to <0, 10> range")
} else {
    print("$randomInt doesn't belong to <0, 10> range")
}

Step 2

We have used a range expression together with the in operator in order to define a condition for the if statement. The condition statement is natural to read and concise. In contrast, an equivalent classic implementation would look like this:

val randomInt = Random(20).nextInt()
if (randomInt >= 0 && randomInt <= 10) {
    print("$randomInt belongs to <0, 10> range")
} else {
    print("$randomInt doesn't belong to <0, 10> range")
}

No doubt, the declarative approach using the range and in operator is cleaner and easier to read, compared to classic, imperative-style condition statements.

Best resources to learn Kotlin

Muhammad Mubeen

Muhammad Mubeen

Mubeen is a full-stack web & mobile app developer who is very proficient in MEAN.js, Vue, Python, Ionic 4, Flutter, Firebase, ROR, and PHP. He has created multiple mobile and web applications. He is very passionate about sharing his knowledge.

Leave a Reply

Your email address will not be published. Required fields are marked *