Understanding Control Flow Statements in Kotlin (with Examples)

Understanding Control Flow Statements in Kotlin (with Examples)

Using if statements, loops, and when expressions in Kotlin

Remi Gathoni's photo
Remi Gathoni
·Aug 4, 2021·

4 min read

Today... we talk about control flow statements in Kotlin.

I have been learning Kotlin and so far, the journey feels both familiar and new at the same time. I came across the when statement and immediately knew I had to write about it. It's everything a switch...case statement is and then more. I love it!

Let’s get started :)

If Statement

Like most programming languages, Kotlin also has an if statement. The if statement works by evaluating code when the provided condition is met.

Syntax

If (condition) {
    // body
}

Take for instance this function that prints a pass if a test result is above 50:

fun assignGrade(result: Int) {
      if(result>=50) {
          print("Pass")
      } 
}
fun main() {
    assignGrade(50)
}

The function accepts a result and checks whether it's 50 or above, if it is, it displays pass.

What about the results below 50? Add an else statement that executes if the condition is not met.

if(result>=50) {
     print("Pass")
} else {
    print("Fail")
}

Now, let's add something for results above 80 and display Excellent. To do this, we will need to add another condition to our function using an else if statement.

if(result>=80) {
     print("Excellent")
}else if (result >=50){
     print("Pass")
}else {
     print("Fail")
}

If the grade is above 80 print Excellent, if it's between 50 and 80, print Pass, and if it's 50 and below print Fail.

One thing you should remember is that Kotlin evaluates if...else as expressions.

Consider a function that determines the maximum number between two numbers. If I was writing JavaScript, I would use a ternary operator. In Kotlin, you don't need to, you can simply use the if statement

max = if (num1 > num2) num1 else num2

Loops

for, while, do...while

For loop

A for loop is used to iterate over... well iterables. These could be arrays, ranges, maps, among others.

Syntax

for(item in iterable) {
    // do something
}

To understand this better, let's look at an example. Say we have an array and we want to print each element in the array, we would use a for loop.

val arr = arrayOf(1,2,3,4)
for(i in arr) {
    print(i)
}

Okay so let's unpack this.

We first assign the array of integers to arr then in the for loop, we iterate over each element in the array and display it.

While

A while loop runs as long as a certain condition is met. You must provide a condition and a modifier in your while loop if you don't want it to run forever.

If we want to display a name until a counter we are keeping track of hits zero, using a while expression is a good option.

var counter = 3

while(counter>0){
     println("Potter")
     counter--
}

Each time the loop runs, it first checks whether the value of the counter is greater than 0.

If it is, it displays the name Potter on a new line and modifies the counter by subtracting 1.

If the counter never gets modified, the condition will always evaluate to true and the loop will never end.

do...while

We've said that while checks a condition first then executes the block, do...while executes the block of code at least once first before it checks the condition.

That's their difference.

Syntax

do {
      // code to run
{
while(condition)

Consider this example:

var counter = 0
do{
    println("Potter")
    counter--
}while(counter>0)

This program displays Potter once.

That's because the program does not check first whether the counter value is greater than 0.

when

If you know about switch...case statements, then you will realize it works nearly the same as the when expression in Kotlin.

Example: Display Monday if the number is 1 and Tuesday if the number is 2, otherwise display an error

when (n) {
    1 -> print("Monday")
    2 -> print("Tuesday")
    else -> {
        print("Error")
    }
}

You could also group the branches. The branches are the 'case statements'.

when (n) {
    in 1..5 -> print("Work Mode")
    6,7 -> print("Weekend Mode")
    else -> {
        print("Error")
    }
}

Now, if you pass in a number between 1 and 5(inclusive), the program will display Work Mode and if you pass in either 6 or 7, you get Weekend Mode.

When can also be used as an expression. Observe...

var whatMode = when (n) {
    in 1..5 -> "Work Mode"
    6,7 -> "Weekend Mode"
    else -> "Error"
}

In the above code, if you passed in 6 as n, the variable whatMode would be Weekend Mode

In this post, we looked at the if statement, for loop, while and do...while loops, and finally the when statement.

If you want to learn more about control flow statements, here is what the Kotlin docs say about them.

Happy Coding :)

 
Share this