Ranges in Kotlin

March 10, 2018 Oclemy Kotlin Range, Kotlin Array 1 minute, 12 seconds

A range is basically an interval with both a start and and an end value.
To create ranges the data types musr be comprabale.
This is done using the range operator(..).

0..9

We then use the in operator to tetst whether a given value is within the defined parameter limits.
A value is said to be within a given range if it is greater than or equal to the start value and less than or equal to the end value.

0..5   //0,1,2,3,4,5

Integers, Longs and Chars ranges can also be used in a for loop.

EXAMPLE 1

fun main(args: Array<String>) {

    for (i in 0..5) {
        println(i)
    }
}

RESULT

0
1
2
3
4
5

EXAMPLE 2

fun main(args: Array<String>) {
    for (i in 3..18 step 3) {
        println(i)
    }
}

RESULT

3
6
9
12
15
18

EXAMPLE 3

fun main(args: Array<String>) {
    for (c in 'a'..'d') {
        println(c)
    }
}

RESULT

a
b
c
d

EXAMPLE 4

fun main(args: Array<String>) {
    for (c in 'a'..'g' step 2) {
        println(c)
    }
}

RESULT

a
c
e
g

To create ranges you can also employ the downTo and rangeTo. downTo creates a range counting down while rangeTo creates a range counting upto a value.
EXAMPLE 5

fun main(args: Array<String>) {
    for (i in 3 downTo 0) {
        println(i)
    }
}

RESULT

3
2
1
0

EXAMPLE 6

fun main(args: Array<String>) {
    val i = 2
    if (i in 1..10) {
        println(i)
    }
}

RESULT

2

EXAMPLE 7

fun main(args: Array<String>) {
    val num = 8
    if (num !in 1..9) {
        println("No there")
    }else
    {
        println("Its there")
    }
}

RESULT

Its there

Comments