Conditional Statements And Expressions

Conditional Statements And Expressions

Hello there👋, welcome back to my blog! In the last t tutorial, we learnt about Kotlin Operators and how to use them.

In this one, we shall learn more about conditional statements and expressions even though we have already implemented some of them in the previous tutorials in this series!

So what are Conditional Statements❓

image.png They are basically programming language commands for handling decisions. They are mainly a bunch of if-then, then-that statements. We can actually call them control flow statements or expressions.

Apart from Python and Kotlin, almost all programming languages have the same conditional statements. So in this tutorial, we shall learn the following:
🔼 If Expression (if..else ....)
🔼 for Loop
🔼 while Loop
🔼 do while Loop
🔼 when expression
🔼 return and jump
🔼 break
🔼 continue

🔹If Expression

In Kotlin, if is an expression is which returns a value. It is used to control the flow of program structure. There is various type of if expression in Kotlin.

◽ if-else expression ◽ if-else if-else ladder expression ◽ nested if expression

if Syntax

if (20 > 18) {

if-else Syntax
if/else works the same way as in Python, but it’s else if instead of elif, the conditions are enclosed in parentheses, and the bodies are enclosed in curly braces:

if (condition) {
  // block of code to be executed if the condition is true
} else {
  // block of code to be executed if the condition is false

if-else if-else Ladder Expression:
This basically goes on to check for another condition if it can be met.

fun main() {  
    val num = 10  
    val result = if (num > 0){  
        "$num is positive"  
    }else if(num < 0){  
        "$num is negative"  
        "$num is zero"  

Unlike in Python, we can actually assign if statements to a variable in Kotlin as seen in the above example. When using if as an expression, you must also include else (required).

Nested if Expression

fun main() {  
    val num1 = 25  
    val num2 = 20  
    val num3 = 30  
    val result = if (num1 > num2){  

        val max = if(num1 > num3){  
        "body of if "+max  
    }else if(num2 > num3){  
        "body of else if"+num2  
        "body of else "+num3  

Note: You can ommit the curly braces {} when if has only one statement:

fun main() {
  val time = 20
  val greeting = if (time < 18) "Good day." else "Good evening."

The above example is similar to the "ternary operator" (short hand if...else) of python function shown below:

# python implementation

def main():
    time = 20 
    greeting = "Good Day" if time < 18 else "Good Evening"
    return greeting

🔹 forLoop

You are likely to use a for loop more often especially if you are using array data structures in your program. They do help in iterating over elements.


val nums = arrayOf(1, 5, 10, 15, 20)
for (x in nums) {

You can use the for loop also to create ranges of values with "..":

for (letters in 'a'..'x') {
  println(letters) // prints the whole alphabet

for (nums in 1..15) {
  println(nums) // prints nums from 1-15

for (i in 5 downTo 1) print(i)  
    println() // prints 5 to 1

Do not forget to wrap the above code in top-level declaration main() so as not to get any errors.

Python For Loop Example that prints 1-15:

for num in range(1,16):
    print(num) # prints nums from 1-15

If you want to exclude the last value, use until:

for (x in 0 until 10) println(x) // Prints 0 through 9

You can also control the increment with step:

# kotlin code
for (x in 0 until 10 step 2) println(x) // Prints 0, 2, 4, 6, 8
# python code
for num in range(0,10,2): print(num) # Prints 0, 2, 4, 6, 8

🔹 while Loop

The while loop is used to iterate a part of the program several times. Loop executed the block of code until the condition has true. Kotlin while loop is similar to Python while loop.

// Syntax
//body of loop  


var num = 0
while (num < 5) {

The while loop executes a block of code to infinite times, if while condition remains true and that means in the above program if we forgot to increase the variable.

🔹 do-while Loop

The do-while loop is similar to while loop except for one key difference. A do-while loop first execute the body of do block after that it checks the condition of while

As a do block of do-while loop executed first before checking the condition, do-while loop executes at least once even the condition within while is false. The while statement of do-while loop end with ";" (semicolon).

// syntax
do {
  // code block to be executed
while (condition);


var i = 1
do {
while (i < 10)

🔹 when

In Kotlin, when expression is a conditional expression that returns the value. It is a replacement of switch statement. Kotlin, when expression works as a switch statement of other languages (Java, C++, C).

In Python, we do not have a switch statement but you can work a way out with dictionary mappings. Read more here

when example:

fun main(){  

    var number = 5 
    when(number) {  
        1 -> println("One")  
        2 -> println("Two")  
        3 -> println("Three")  
        4 -> println("Four")  
        5 -> println("Five")  
        else -> println("invalid number")  


# This should print 5, keep changing the variable to see the different outcomes

You can also use when as an expression lie this:

fun main(){  
    var number = 5  
    var numProvided = when(number) {  
        1 -> "One"  
        2 -> "Two"  
        3 -> "Three"  
        4 -> "Four"  
        5 -> "Five"  
        else -> "invalid number"  
    println("You provided $numProvided")  

An expression basically consists of variables, operators, methods calls etc that produce a single value.

We can also use multiple statements enclosed within the block of conditions.

fun main(){  
    var number = 1  
    when(number) {  
        1 -> {  
            println("Today is Monday")  
            println("First day of the week") 
            println("Go for it >>>")  
        7 -> println("Sunday")  
        else -> println("Other days")  

🔸 Kotlin has three structural jump expressions:

return: by default returns from the nearest enclosing function or anonymous function.
break: terminates the nearest enclosing loop.
continue: proceeds to the next step of the nearest enclosing loop.

These jump expressions are used to control the flow of program execution and they exactly work the same way as those in Python.

🔹 return

As opposed to Python, omitting return at the end of a function does not implicitly return null; if you want to return null, you must do so with return null.

If a function never needs to return anything, the function should have the return type Unit (or not declare a return type at all, in which case the return type defaults to Unit). In such a function, you may either have no return statement at all or say just return.


fun foo(ints: List<Int>) {
    ints.forEach {
        if (it == 0) return

return with labels

return@name or return@label determinates for which closure return statement should be applied. Usually, you can omit @label.

In Kotlin, you can call return from nested closure to finish outer closure.

fun foo(ints: List<Int>) {
    ints.forEach {
        if (it == 0) return@forEach // implicit label for lambda passed to forEach

Unit is both a singleton object (which None in Python also happens to be) and the type of that object, and it represents “this function never returns any information” (rather than “this function sometimes returns information, but this time, it didn’t”, which is more or less the semantics of returning null).

🎗 it keyword explained briefly
Whenever you have a function literal with exactly one parameter you don’t have to define the parameter explicitly but you can just use it.

This makes a lot of the language constructs map, filter, etc easier to use as you do not have to specify the name of the parameter (you can if you want to).

In conventional programming when you loop through a collection you might do:
for (element in collection) { println(element) }

When using Kotlin functional features you can do something like: { println(it) }

🔹 break

The break statement is used to jump out of a loop. Example:

fun main() {  
    for (i in 1..100) {  
        if (i == 41) {  

Any expression in Kotlin may be marked with a label. Labels have the form of an identifier followed by the @ sign, for example: abc@, fooBar@. To label an expression, just add a label in front of it. Example:

fun main() {  
loop@ for (i in 1..100) {
    for (j in 1..100) {
        if (j==41) break@loop


Read more about labels and returns here

🔹 continue

Kotlin, continue statement is used to repeat the loop. It continues the current flow of the program and skips the remaining code at specified condition.

The continue statement within a nested loop only affects the inner loop.

fun main() {  
        for (i in 1..3) {  
            println("i = $i")  
            if (i == 2) {  
            println("this is below if")  
/* expected output
i = 1
this is below if
i = 2
i = 3
this is below if

Kotlin labelled continue example

fun main(args: Array<String>) {  
    labelname@ for (i in 1..3) {  
    for (j in 1..3) {  
        println("i = $i and j = $j")  
        if (i == 2) {  
        println("this is below if")  


Well, we have come to the end of this tutorial, you can read more from the official docs here: If you liked the article, consider following me for more in the series as we continue learning and developing with Kotlin.

Follow me on Twitter . See Yah 🥰>>>

Ronnie Atuhaire 😎