Instruction

Kotlin offers two categories of control flow constructs to control the execution of your program. These are:

  • Conditional flows: Involve decision-making and branching based on a specific arithmetic, logical, or relational condition.
  • Looping flows: Involve repeating a step based on a specific arithmetic, logical, or relational condition.

Let’s look at both in more detail.

Exploring Conditional Flows

With conditional flows, you can structure your code so certain sections run based on a condition being met, while a different section runs if the condition isn’t met. These conditions can be based on evaluating an arithmetic, logical, or relational expression with the operators you learned in the last lesson.

Kotlin offers two conditional constructs.

Using if-else Conditions

In Kotlin, an if statement evaluates an expression that returns a Boolean value. Based on the Boolean value, it then executes the code in the body of the if expression:

val age = 21
var person = "child"

// 1
if (age > 18) {
  // 2
  person = "adult"
}

println(person)

In the snippet above:

  1. The if condition evaluates to true since age is greater than 18.
  2. The value of person is then reassigned to "adult".

Adding an’ else’ statement can also make the structure more sophisticated. That will be executed in case the if expression evaluates to false. Here’s what that looks like:

val a = 20
val b = 100
// 1
var max = a

// 2
if (a > b) {
  max = a
} else {
  // 3
  max = b
}

println(max)

In this snippet:

  1. max is initially assigned to a.
  2. The if condition is evaluated to be false, so the execution jumps to the else block.
  3. The value of max is reassigned to b.

You can also chain several if-else conditions in an if-else ladder, as shown below:

// 1
val age = 13

// 2
val result = if (age > 19) {
    "Adult" 
  } else if ( age > 12 && age < 20 ) {
    "Teen" 
  } else {
    "Minor" 
  }

// 3
println(result)

In this snippet:

  1. You assigned age to the value 13.
  2. You then used an if-else ladder, which results in a string value being returned and assigned to the result variable.
  3. In this case, result is assigned a value of "Teen".

The snippet above uses evaluated expressions to assign a value to result. It’s a simpler, more concise way of writing the following:

val age = 13 
var result = ""
if (age > 19) {
  result = "Adult" 
} else if ( age > 12 && age < 20 ) {
  result = "Teen" 
} else {
  result = "Minor" 
}

println(result)

Using when Expression

When defines a conditional expression with multiple branches. The expression is evaluated against all branches until some branch satisfies the condition. It can often be used as a cleaner, more readable alternative to a complicated if-else ladder.

Here’s an example:

val age = 13
var result = ""

when {
  age > 19 -> {
    result = "Adult"
  }

  age >= 13 && age <= 19 -> {
    result = "Teen"
  }

  else -> {
    result = "Minor"
  }
}

println(result)

The snippet above is similar to the if-else ladder seen previously. In the when expression, the conditions are specified as distinct branches and each condition is checked in order. If a condition is satisfied, the corresponding result is assigned to the result variable.

This can be further simplified by using the evaluated expression syntax as follows:

val age = 13
var result = when {
 age > 19 -> "Adult" 

 age >= 13 && age <= 19 -> "Teen" 
 
 else -> "Minor"
}

println(result)

Looping Flows

Looping flows are used when you want to repeat a step until a given condition is no longer met. Kotlin offers three looping constructs:

  • for loop
  • while loop
  • do-while loop

Using For Loop

For loop iterates through anything that provides an iterator. It can be a range of numbers, a collection of objects, or an array.

Here are a few examples:

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

In this example, the loop iterates over the range 1 to 5 and prints each number to the console.

val fruits = arrayOf("Apple", "Banana", "Orange")
for (item in fruits) {
  println(item)
}

In this example, the loop iterates over an array of strings and prints out each item to the console.

You can also use for loops to iterate over characters in a string.

val fruit = "Apple"
for (letter in fruit) {
 println(letter)
}

In this example, the console will print each of the letters of the word apple.

Using While Loop

The while loop executes its body until the expression specified isn’t met.

Here’s what it looks like:

var i = 0 
while (i < 5) { 
  print(i)   //prints 01234
  i++ 
}

In this example, the while loop will run from 0 to 4 and print the value to the console.

With While loops, you need to be careful that the condition becomes false at some point, otherwise it can execute forever or until your computer crashes.

Using do-while Loop

The do-while loop is very similar to the while loop, which executes its body until the specified expression isn’t met. Here’s what it looks like:

var i = 0 
do { 
  print(i)   //prints 01234
  i++ 
} while (i < 5)

The difference between while and do-while is that while will first check for the condition and only then execute the body. Whereas do-while will first execute the body and then check for the condition.

Meaning, in case the specified condition is never met, the do-while loop’s body will still execute once, whereas the while loop will never execute its body:

var i = -1
while (i > 0) { 
  print(i)   //prints nothing to the console
  i-- 
}

do { 
  print(i)   //prints -1 to the console
  i-- 
} while (i > 0)

In this snippet above:

  • The while loop never executes as the condition is always false.
  • The do while executes its body once and prints -1 to the console.

Using Break and Continue

When using loops, you may want to terminate a loop or skip an iteration prematurely. To do so, Kotlin offers the break and continue keywords.

You can use break to terminate the loop prematurely, as shown below:

  var count = 0
  while (count < 10) {
    println(count)
    count++
    if (count == 4) {
      break
    }
  }

The snippet above starts an iteration from 0 and keeps incrementing the value of count and printing it to the console. As soon as the value of count becomes four, it executes the break statement and terminates the loop.

In cases where you want to run the loop but skip a few iterations, you can use continue. Here’s an example:

var count = 0
while (count < 10) {
  if (count % 2 == 0) {
    count++
    continue
  }
  println(count)
  count++
}

In the loop above, every even number will be skipped, and only odd numbers will be printed.

Here’s an example of a simple fruit-sorting program that uses break and continue to sort the fruits by color.

// 1
val fruits =
        listOf(
            "apple",
            "kiwi",
            "lime",
            "strawberry",
            "watermelon",
            "cherry",
            "mango",
            "banana",
            "orange"
        )

// Green bin
val greenBin = mutableListOf<String>()

// 2
for (fruit in fruits) {
  if (fruit == "apple" || fruit == "kiwi" || fruit == "lime") {
    // 3
    greenBin.add(fruit)
    continue // Keep adding green fruits
  }
  // 4
  break // Move to next bin if not green
}

// Red bin
val redBin = mutableListOf<String>()
for (fruit in fruits) {
  if (greenBin.contains(fruit)) continue // Already sorted in green bin

  // 5
  if (fruit == "strawberry" || fruit == "watermelon" || fruit == "cherry") {
    redBin.add(fruit)
    continue // Keep adding red fruits
  }
  // 6
  break
}

// 7
println("Green bin: $greenBin")
println("Red bin: $redBin")

In the snippet above you:

  1. Create a list of fruits
  2. Loop over a list of fruits.
  3. For every fruit that is green, you add it to the greenBin list and skip the current iteration.
  4. If no green fruits are found, you terminate the loop.
  5. Similarly, for every fruit that is red, you add it to the redBin list and skip any fruits that are already in the greenBin.
  6. If no more red fruits are found, you terminate the loop.
  7. Print both lists to the console.
See forum comments
Download course materials from Github
Previous: Introduction Next: Demo