Kotlin Conditional Statements: When, While, For Loop, If Else

By Sruthy

By Sruthy

Sruthy, with her 10+ years of experience, is a dynamic professional who seamlessly blends her creative soul with technical prowess. With a Technical Degree in Graphics Design and Communications and a Bachelor’s Degree in Electronics and Communication, she brings a unique combination of artistic flair…

Learn about our editorial policies.
Updated March 7, 2024

Learn about Kotlin Conditional Statements such as When, While, For Loop, If Else, etc with the help of programming examples:

In this tutorial, we will learn about the control flow statements provided by Kotlin.

These statements are used in the application to validate certain conditions and perform different tasks depending on the condition evaluation. For example – a calculator application would need to perform different operations depending on the type of functionality chosen by the user – as add/multiply / subtract, etc.

=> Read ALL Our Kotlin Tutorials Here

Kotlin Conditional Statements

Kotlin Conditional Statements

Primarily, there are 4 types of control flow constructs provided by Kotlin i.e. when, if-else, while, and for loops. You can learn more about them here.

Kotlin when

“when” statement in Kotlin is similar to using “switch-case” statements for those familiar with using other programming languages like Java and C#.

Depending on the different values of the constant or variable within the when expression, different statements can be executed.

(Note: when statement can also be rewritten using a combination of multiple – if – else-if blocks but it makes the statement or loop more complex and less readable)

Let’s understand when statement with the help of different examples:

Simple “when” Statement With Integer Value

Let’s write a when statement to print a number as even or odd

fun main() {
    // input a number
    val reader = Scanner(System.`in`)
    print("enter a number:")

    // read a number for user keyboard
    val number: Int = reader.nextInt()
    when(number%2) {
        0 -> println("$number is even")
        1 -> println("$number is odd")
    }
}

//Output
enter a number:10
10 is even

enter a number:15
15 is odd

Here we have used – “number%2” as when condition and depending on the evaluated value of this condition i.e. 0 or 1 – we print whether the number is even or odd.

Using else Block as Default Block

With when statements – we can add an optional else block – which would be invoked for any non-matching values.
Let’s hypothetically consider a function – that returns a number as valid if it’s greater than 5, else returns it as invalid.

Let’s try to express this as a when statement

fun main() {
    val reader = Scanner(System.`in`)
    print("enter a number:")
    
    // read a number for user keyboard
    val number: Int = reader.nextInt()
    when {
        number > 5 -> println("$number is valid")
        else -> println("invalid number: $number")
    }
}

// Output
enter a number:3
invalid number: 3

Here it’s important to note that

  • We are not explicitly supplying any condition within when block – but using expressions evaluated as a part of the when body itself – like number > 5
  • else block – serves as a default block, which would be invoked for any number that’s less than 5.

Using Range Values in when Block

Let’s see how we can use a range of values inside the when statement body.

Suppose, we want to create a function to greet depending on the hour of the day.

fun main() {
    val reader = Scanner(System.`in`)
    print("enter hour:")

    // using user input directly inside when block
    when(reader.nextInt()) {
        in 0..11 -> println("Good Morning!!")
        in 12..16 -> println("Good Afternoon!!")
        in 17..20 -> println("Good evening!!")
        in 21..24 -> println("Good Night!!")
        else -> println("Not a valid hour value")
    }
}

//Output
enter hour:12
Good Afternoon!!

Using when Statements to Return Value

Instead of printing the results depending on the matched condition, when blocks can also return value to the variable it’s assigned to.

For Example, let’s use the even/odd example to return a value to a variable oddOrEven.

fun main() {
    val reader = Scanner(System.`in`)
    print("enter number:")
    val number = reader.nextInt()
    val oddOrEven = when {
        number%2 == 1 -> "odd"
        else -> "even"
    }
    println(oddOrEven)
}

//Output
enter number:14
even

Here, we have used the when body to have the returned value stored in a variable odd or even.

Kotlin if-else

Kotlin provides the “if” condition/statement to be used to evaluate a simple/complex condition and perform a separate set of statements depending on the condition evaluation being true or false.

Different variations of the if statement are available:

  • Pure ‘if’ without any else block: Here only if a block is available and is executed if the condition is evaluated to true. For example, let’s take a number as Input and if number > 50 we would print the message – the number is too big!
fun main() {
val reader = Scanner(System.`in`)
print("enter a number:")
val number: Int = reader.nextInt()

if(number > 50) {
println("number is too big!")
}
}

//Output
enter a number: 100
number is too big!
  • if-else – one block each for if and else – Let’s extend the above example and print “number is small” if the condition does not evaluate to true.
fun main() {
val reader = Scanner(System.`in`)
print("enter a number:")
val number: Int = reader.nextInt()

if(number > 50) {
println("number is too big!")
} else {
println("number is small")
}
}

//Output
enter a number: 50
number is small
  • if-elseif-else – multiple elseif blocks and final else block – Let’s now see, how we can use a combination of multiple else-if blocks when there is a need to evaluate conditions and print different outputs.

Suppose we want to find a maximum of 3 numbers that are entered by the user – we can use if-else along with an else if block as below:

fun main() {
val reader = Scanner(System.`in`)
print("enter first number:")
val number1: Int = reader.nextInt()
print("enter second number:")
val number2: Int = reader.nextInt()
print("enter third number:")
val number3: Int = reader.nextInt()

if(number1 >= number2 && number1 >= number3) {
println("number1 ($number1) is greatest")
} else if(number2 >= number3 && number2 >= number1) {
println("number2 ($number2) is greatest")
} else {
println("number3 ($number3) is greatest")
}
}

//Output
enter first number:30
enter second number:30
enter third number:50
number3 (50) is greatest

Notes on Short-circuiting

With ‘if’ expressions and Boolean conditions combined, Kotlin will try to short circuit or skip the rest of the evaluation depending on the Boolean operator being used.

For example, Suppose we have a condition with Boolean OR operator

condition1 || condition2 => here if condition1 is evaluated to be true, Kotlin compiler would short circuit and return true as there’s an OR condition which would anyways evaluate to true irrespective of the result of condition2 being evaluated to true or false.

Kotlin for loop

A loop in general is used to perform a given task a repeated number of times. Kotlin provides a “for” loop to execute a task a given number of times.

This is similar to for loop in other programming languages like Java and C#.

Syntax of for loop:

for(<constant> in <range>) {
// 1 or more statements to be executed
}

In contrast to other programming languages, Kotlin has a concept of range to define the values over which the loop would execute.

There are different ways of defining the range values.

  • Closed range: Includes both start and end numbers – defined as 0..5 (would include numbers from 0 to 5 – both 0 & 5 inclusive)
  • Half open range: Includes start index but excludes end index – defined as 0 until 5 (would include numbers 0,1,2,3 & 4)
  • Decreasing range: Can be created using downTo keyword – 5 downTo 0 (would include numbers – 5,4,3,2,1,0)
    Note: For close and half-open range – the values should always be increasing i.e., end index needs to always be greater than the start index.

Let’s have a look at a few examples of using “for” loops.

Simple for loop with Closed Range

fun main() {
var sum = 0;
for(i in 1..5) {
sum += i
}
println("sum is : $sum")
}

//Output
sum is : 15

In the above example – i is iterated from 0 to 5, & the value of i is added to the sum during each iteration.

sum = 0 + 1 + 2 + 3 + 4 + 5 => 15

For loop with Half Open Range

Let’s try the same example with a half-open range (which would not include the upper range).

fun main() {
    var sum = 0;

    // using until / half open range in for loop
    for(i in 1 until 5) {
        sum += i
    }
    println("sum is : $sum")
}
//Output
sum is : 10

Here – the upper range 5 would be excluded
sum = 0+1+2+3+4 => 10

For loop with step

Modifying “step” value in for loop – let’s say instead of incrementing the constant by 1 – we want to do it by some other number – ex – 2

Let’s use for loop to print all odd numbers between 1 & 10.

fun main() {
for(i in 1..10 step 2) {
println(i)
}
}

//Output
1
3
5
7
9

Using for loop to Print Elements in List

For loop can also be useful to iterate over collections like lists, arrays, maps, etc, and print values or perform different operations.

fun main() {
val listCourses = listOf("Computer", "Electronics", "Civil")
for(course in listCourses) {
println(course)
}
}
// Output
Computer
Electronics
Civil

For loop variation – repeat

Let’s discuss another variation of for loop – “repeat” – it is used to execute a certain statement for a repeated number of times without any constant or range.

fun main() {
var count = 0
repeat(5) {
println("repeat count $count")
count ++
}
}

//Output
repeat count 0
repeat count 1
repeat count 2
repeat count 3
repeat count 4

Kotlin while

Similar to “for”, “while” is another type of loop provided by Kotlin. While loop would execute a block of code until the condition specified in the while expression is evaluated to true.

Syntax:

while(condition) {
// 1 or more statements to be executed
}

Let’s see an example: we have a count variable initialized to 5 – we want to create a while loop which would execute until count > 0 (and the count would be reduced by 1 after each iteration).

fun main() {
var count = 5
while(count > 0) {
println("count is $count")
count --
}
}
//Output
count is 5
count is 4
count is 3
count is 2
count is 1

Another variant of the while loop is a do-while loop – it differs from the while loop in the way the condition evaluation happens – in do-while, the code block executes before the condition is evaluated while in a normal while loop unless the condition evaluates to true, the statements would not be executed.

Let’s understand this with the help of an example: In the while loop example – let’s change the initial value of count to 0 (instead of 5)

We would see that the actual condition would be evaluated to be false, but the control flow statements would still execute once, with the do-while loop.

fun main() {
var count = 0
do {
println("count is $count")
count --

} while(count > 0)

}
//Output
count is 0

Breaking out of a loop

At times, depending on the condition evaluation, you might want to come out of the currently executing loop, thereby skipping the rest of the iterations within the loop. This can be achieved by using the “break” statement within the loop.

As soon as the “break” statement is encountered, the control flow moves out of the immediate loop/control flow block.

Let’s understand this with the help of an example: Suppose we have a while loop that works on the value of count and runs till count < 0 – Suppose we want to come out of the loop as soon as the value of count reaches 2

fun main() {
var count = 5
while(count > 0) {
println("count is $count")
count --
if(count == 2) {
break
}
}
println("break statement encountered at count = $count")
}

//Output
count is 5
count is 4
count is 3
break statement encountered at count = 2

Frequently Asked Questions

Q #1) Why is there no ternary in Kotlin?

Answer: Kotlin does not have a ternary operator as opposed to other languages like Java. However, we can make use of the if-else block and return value depending on the evaluation.

fun main() {
    val reader = Scanner(System.`in`)
    print("enter number:")
    val number = reader.nextInt()
    val evenOdd = if(number%2 ==0) "even" else "odd"
    println(evenOdd)
}

//Output
enter number:14
even

In the above example, you can see – we have used an if-else block to assign value to a variable – evenOdd depending on the condition expressed in if-else block.

Q #2) How do you make a loop in Kotlin?

Answer: Kotlin supports different kinds of loop using – for, while, and do-while expressions. Let’s have a look at an example of using a for a loop – suppose you want to print all integers between 1 & 10 – you can use a for loop for this.

fun main() {
for (i in 1..10) {
println(i)
}
}

Q #3) How do you break “when” Kotlin?

Answer: Kotlin provides 3 types of jump expressions – return – to return the code to the calling function, break – terminate the nearest loop, continue – move to the next iteration of the loop (applies to for or repeat).

In order to “break” a when condition, in Kotlin

  • You are not mandated to write a break after each when block – as soon as the current match is done – the control moves out of the when block on its own.

Also please note, that in the case of the “when” block – even if there are multiple matches – as soon as the first condition is matched – the associated expression block gets executed and the code moves out of the when expression.

Q #4) What is the use of when in Kotlin?

Answer: when is a type of conditional expression supported by Kotlin, and is generally used when you have to compare a value against multiple known values and perform different operations against it. A simple example to understand this can be to greet a user depending on the value of the hour of the day.

Conclusion

In this tutorial, we learned about different conditional expressions supported by Kotlin. We learned about loops like – for, while, and do-while and their variants like “repeat” etc.

We also learned about conditional evaluation like – when block and if-else block. All these expressions are heavily used in applications that use Kotlin as the programming language and knowledge of these is an essential element to succeed in Kotlin programming.

PREV Tutorial | NEXT Tutorial

Was this helpful?

Thanks for your feedback!

Leave a Comment