Instruction

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

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.

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)
val a = 20
val b = 100
// 1
var max = a

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

println(max)
// 1
val age = 13

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

// 3
println(result)
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.

val age = 13
var result = ""

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

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

  else -> {
    result = "Minor"
  }
}

println(result)
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:

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.

for (i in 1..5) {
  println(i) 
}
val fruits = arrayOf("Apple", "Banana", "Orange")
for (item in fruits) {
  println(item)
}
val fruit = "Apple"
for (letter in fruit) {
 println(letter)
}

Using While Loop

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

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

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)

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)

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.

  var count = 0
  while (count < 10) {
    println(count)
    count++
    if (count == 4) {
      break
    }
  }
var count = 0
while (count < 10) {
  if (count % 2 == 0) {
    count++
    continue
  }
  println(count)
  count++
}
// 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")
See forum comments
Download course materials from Github
Previous: Introduction Next: Demo