Kotlin Control Flow – if else, for loop, while, range

Filed Under: Kotlin

In this tutorial, we’ll be covering an important aspect of programming, namely Kotlin Control Flow statements.
We’ll look into the if else, range, for, while, when repeat, continue break keywords that form the core of any programming language code.

Let’s get started with each of these operators by creating a Kotlin project in our IntelliJ Idea.
kotlin control flow, kotlin if else, kotlin for loop

Kotlin if else

In Kotlin, if else operators behave the same way as it does in Java.
if executes a certain section of code if the condition is true. It can have an optional else clause.
Following code is from the Test.kt class in our IntelliJ Project.


fun main(args: Array<String>) {

    var a = 4
    var b = 5

    var max = a
    if (a < b)
        max = b

    if (a > b) {
        max = a
    } else {
        max = b
    }

    println("a is $a b is $b max is $max")
}

In Kotlin, if else can be used as expressions too in order to return a value.


    a = 5
    b = 4


    //if else returns a value in Kotlin
    max = if (a > b) a else b

    print("a is $a b is $b max is $max")

This way Kotlin eliminates the use of ternary operator by using if else as expressions.

In another view, the last statement present in an if else condition is returned as the value.
The below example demonstrates the same.


max = if(a>b)
    {
        println("a is greater than b")
        println("max is a")
        a
    }
    else{
        println("b is greater than a")
        println("max is b")
        b
    }

    println("max is $max")

//Following is printed on the log console.

a is greater than b
max is a
max is 5

Kotlin for loop

The syntax of for loop in Kotlin is different from the one in Java.
For loop is used to iterate over a list of items based on certain conditions.
Following is the implementation of for loops in Kotlin to print numbers 0 to 5.


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

Few inferences from the above syntax are listed below:

  • Kotlin saves us from declaring the type of i
  • The lower and upper (including) limits are be defined on either side of .. operator.
  • in keyword is used to iterate over the range.

Another case for you, where we iterate over an array using for-in loop.


val items = listOf(10, 20, 30, 40)

    for (i in items)
        println("value is $i")

//Following is printed to the console.
value is 10
value is 20
value is 30
value is 40

To print the index of the elements, we invoke the indices method on the arrays.


val items = listOf(10, 20, 30, 40)

    for (i in items.indices)
        println("value is $i")

//Following is printed to the console:
value is 0
value is 1
value is 2
value is 3

To access the index and value of the element in the iteration, withIndex() function is used.


val items = listOf(10, 20, 30, 40)

    for ((i,e) in items.withIndex())
        println("index is $i and element is $e")

//Following is printed on the console:
index is 0 and element is 10
index is 1 and element is 20
index is 2 and element is 30
index is 3 and element is 40

Kotlin forEach loop

ForEach loop repeats a set of statements for each iterable as shown below.


(2..5).forEach{
        println(it)
    }

//or

(2..5).forEach{
      i ->  println(i)
    }

//Following is printed on the console:
2
3
4
5

it is the default iterable variable that holds the value of the current iterator.
In the second case, we’d use our own custom variable.

Kotlin Range

We’ve seen in the above sections that .. operators represents a range.


(2..4).forEach{
        println(it)
    }

//Following gets printed on the console:
2
3
4

To check whether an element exists or doesn’t exist in a range we use the in and !in keywords as shown below.



var x = 5

    if(x in 1..10)
    {
        print("x exists in range") //this gets printed
    }
    else{
        print("x does not exist in range")
    }

x = 15

    if(x !in 1..10)
    {
        print("x does not exist in range") //this gets printed
    }
    else{
        print("x does exist in range") 
    }

And the following should work the same way. Right?


var x = 5

    if(x in 10..1)
    {
        print("x exists in range")
    }
    else{
        print("x does not exist in range") //Ironically, this gets printed.
    }

for (i in 5..0) 
print(i) //prints nothing

NO.
The Range .. can’t be used in the reverse order.
This is where we use the downTo keyword.

The below code would work:


var x = 5

    if(x in 10 downTo 1)
    {
        print("x exists in range") //this gets printed
    }
    else{
        print("x does not exist in range")
    }

for (i in 5 downTo 0) 
print(i) //543210


To exclude the last element from the range we use the keyword until.


for (i in 1 until 4) {
     print(i)
}
//prints 123

To traverse the range in steps we use the keyword step.


for (i in 1..5 step 3) print(i) // prints 14

for (i in 4 downTo 1 step 2) print(i) // prints 42

Kotlin while loop

while and do-while loops in Kotlin behave the same way as they do in Java.


var i = 0
    do {
        i+=5
        println("Value of i is $i") //prints 5
    } while(i<1)


i=0
    while(i<=5) {
        print(i)
        i++
    }

//prints 012345

Kotlin break and continue

break is used to exit the loop there and then.
continue is used to go to the next iteration of the loop.
Kotlin gives us the luxury to attach a label to the break and continue statements to indicate the loop on which their actions are triggered as shown below.


customLabel@ for(y in 10 downTo 5) { // applying the custom label
        if(y == 6) {
            print("x is $y breaking here")
            break@customLabel //specifing the label
        } else {
            print("continue to next iteration")
            continue@customLabel
        }
    }

Kotlin repeat and when

repeat allows us to execute the statements in the loop N number of times(where N is the number specified as the argument).
The following code snippet would print the group of statements 3 times.


repeat(3) {
        println("Hello World!")
        println("Kotlin Control Flow")
    }

when in Kotlin is equivalent to switch in other languages, though with a different syntax and more power!
A basic example of when operator is given below.


var num = 10
    when (num) {
        0 -> print("value is 0")
        5 -> print("value is 5")
        else -> {
            print("value is neither 0 nor 5") //this gets printed.
        }
    }

The when operator matches the argument with all the branches. If it matches with none, the else statement is printed. The else statement is similar to default in switch.
when operator can be used to return values too, similar to if else.


var valueLessThan100 = when(101){
        in 1 until 101 -< true
        else -> {
            false
        }
    }
    
    print(valueLessThan100) //false

Going further, we can use Any type to check the branch as shown below.


fun month(month: Any)
{
    when(month)
    {
        1 -< print("January")
        2-< print("February")
        "MAR" -< print("March")
        else -> { print("Any other month or it is invalid. when operator takes generic type Any") }
    }
}

month(1) //"January"
month("MAR") //"March"

Kotlin Control Flow Statements Example

Summing up the control flow in our Kotlin project, this is how our Kotlin class file looks:


fun main(args: Array<String>) {

    var a = 4
    var b = 5

    var max = a
    if (a < b)
        max = b

    if (a > b) {
        max = a
    } else {
        max = b
    }

    println("a is $a b is $b max is $max")

    a = 5
    b = 4


    //if else returns a value in Kotlin
    max = if (a > b) a else b

    println("a is $a b is $b max is $max")


    max = if(a>b)
    {
        println("a is greater than b")
        println("max is a")
        a
    }
    else{
        println("b is greater than a")
        println("max is b")
        b
    }

    println("max is $max")

    val items = listOf(10, 20, 30, 40)

    for ((i,e) in items.withIndex())
        println("index is $i and element is $e")

    (2..5).forEach{
        print(it)
    }

    var x = 5

    if(x in 10 downTo 1)
    {
        print("x exists in range")
    }
    else{
        print("x does not exist in range")
    }

    var i = 0
    do {
        i+=5
        println("Value of i is $i")
    } while(i<1)


    i=0
    while(i<=5) {
        print(i)
        i++
    }


    customLabel@ for(y in 10 downTo 5) { // appling the custom label
        if(y == 6) {
            print("x is $y breaking here")
            break@customLabel //specifing the label
        } else {
            print("continue to next iteration")
            continue@customLabel
        }
    }

    repeat(3) {
        println("Hello World!")
        println("Kotlin Control Flow")
    }

    var num = 10
    when (num) {
        0 -> print("value is 0")
        5 -> print("value is 5")
        else -> {
            print("value is neither 0 nor 5")
        }
    }

    var valueLessThan100 = when(101){
        in 1 until 101 -> true
        else -> {
            false
        }
    }

    print(valueLessThan100) //false


    month(1)
    month("MAR")


}

fun month(month: Any)
{
    when(month)
    {
        1 -> print("January")
        2-> print("February")
        "MAR" -> print("March")
        else -> { print("Any other month or it is invalid. when operator takes generic type Any") }
    }
}

This brings an end to this tutorial
References: Kotlin Official Doc, Range API Doc

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages