Loops and conditions are foundational concepts for formulating algorithms in software programs.
Looping constructs allow the programmer to continuously execute a sequence of instructions until a given condition is met. They can also be used to iterate through something with sequential values such as a string or an array collection.
In this article, we’ll take a look at some basic and advanced ways to use conditions and loops in Kotlin. We will cover:
if
with else
in Kotlin conditional expressionswhen
with else
in Kotlin conditional expressionsfor
loopswhile
and do...while
break
and continue
to control loop executionIn Kotlin, there are several data structures that could contain a sequence of values. Some examples of these Kotlin data structures include strings, arrays, ranges, and maps.
Oftentimes, you might want to iterate over their values for various reasons. For example, maybe you want to find a particular item in a list, or you want to multiply each number in an array by two, or you want to get a subset of a string.
Whatever the case, the for
loop allows you to iterate over the collection and sequentially access each individual value in the collection. Technically, you can iterate over anything in a for
loop as long as it provides an iterator — like strings, arrays, ranges, and so on.
When an iteration achieves its purpose — such as finding a given item in a list — it has to be terminated. The most common way of achieving this is through the use of conditional expressions inside the loop.
A conditional expression is one that evaluates to either true
or false
. In Kotlin, the three control statements used to evaluate conditional expressions are if
, else
, and when
.
An if
statement allows you to specify code that should run if a conditional expression evaluates to true
, whereas when
allows you to specify multiple code branches to run depending on the actual value of a conditional expression.
In addition, an else
block can be nested within both if
and when
statement to specify an alternative code to run if the condition evaluates to false
.
Both if
and when
can be used as expressions. In that case, the value of the first matching branch becomes the value of the whole expression. This makes it possible to use them in the same way you would use the ternary operator in other languages, like JavaScript.
Going back to loops, you can perform an if
check on each iteration and terminate the loop at the point where the check evaluates to true
.
You’ll learn about this and more in the following sections.
if
with else
in Kotlin conditional expressionsLet’s start with the basics.
In Kotlin, if
is used to execute a sequence of instructions (code) if a given conditional expression evaluates to true
. For example, in the following code block, if
checks whether variable a
is greater than variable b
. If so, it sets the variable aIsGreater
to true
.
var a:Int = 25 var b:Int = 10 var aIsGreater:Boolean = false if (a > b) aIsGreater = true println(aIsGreater) // prints true
You’ll sometimes want to execute a separate block of code if the specified condition evaluates to false
. This is done using else
.
Going back to our first example, if a
is not greater than b
, we’ll instead assign false
to the variable aIsGreater
and print the output. We’ll also swap the values for a
and b
so that b
is greater than a
. The code is as follows:
var a:Int = 10 var b:Int = 25 var aIsGreater:Boolean = false if (a > b) { aIsGreater = true } else { aIsGreater = false } println(aIsGreater)// prints false
You can also use if
in a conditional expression — so again, there is no need for a ternary operator in Kotlin:
// Used as an expression: val aIsGreater = if (a > b) true else false // "if" expression can also have blocks: val aIsGreater = if(a > b) { true } else { false }
Anytime if
is used in a conditional expression and has code blocks as branches, then the last expression in the block is the value of the block. In the example above, that could be either true
or false
depending on the conditional expression.
when
with else
in Kotlin conditional expressionsNext, we have when
, which evaluates a condition and sequentially compares the value with those in its branches. If there is a match, it’ll execute the corresponding code. Otherwise, it’ll fall back to the else
block.
The else
block is required if the branches inside when
don’t cover all possible cases. In the following example, the variable day
is set to 1
. As a result, the code on the first branch will be executed:
val day:Int = 1 when (day) { 1 -> print("Today is Monday!") 2 -> print("Today is Tuesday!") 3 -> print("Today is Wednesday!") 4 -> print("Today is Thursday!") 5 -> print("Today is Friday!") 6 -> print("Today is Saturday!") else -> { print("Oh, so it's Sunday then") } }
Assume that we set the day to 7
, which doesn’t match any of the values on the branches. Upon running the code, the else block would run, outputting Oh, so it’s Sunday then
.
You can also define common behavior for multiple cases. For example, in the following when
block, we output the same message for days 1
, 2
,and 3
:
val day:Int = 1 when (day) { 1, 2, 3 -> print("It's any of the first three days of the week") 4 -> print("Today is Thursday!") 5 -> print("Today is Friday!") 6 -> print("Today is Saturday!") else -> { print("Oh, so it's Sunday then") } }
You can also use the in
expression within a when
block in two cases. First, to check if an item is in a collection. Otherwise, to check if the numerical value returned from the conditional expression is in a given range. The following example demonstrates both cases:
val today = 8 val daysOfTheWeek = arrayOf(1, 2, 3, 4, 5, 6, 7) when (today) { in 1..7, in daysOfTheWeek -> print("This is a valid day and part of the weekdays!") !in 1..7 -> print("This is not a valid day!") else -> { print("Neither of the two") } }
To be clear, we did not have to define the else
block in the example above because the branches in the when
block cover all possible cases — either it’s a day of the week, or it’s not. I just left it there to be complete and thorough.
for
loopsIn Kotlin, the for
looping construct is used to cycle through an iterable and perform a consistent action on every iteration instance.
Let’s say you have a collection of fruits, and for each fruit, you want to print its name and index. Here’s how to do that in Kotlin using the for
loop:
val fruits = arrayOf("orange", "apple", "mango", "pear", "banana") for (i in 0..fruits.size-1) { println(fruits[i] + " "+ "is at index"+ " " + i) }
Here’s the output:
orange is at index 0 apple is at index 1 mango is at index 2 pear is at index 3 banana is at index 4
You can also iterate over a range of numbers using a range expression:
for (i in 1..10) { println(i) // prints 1-10 }
Or define more advanced looping methods, such as iterating backward and only counting on every three steps:
for (i in 12 downTo 0 step 3) { println(i) }
downTo
is used to iterate through numbers in reverse order. So in the example above, we’re counting down from twelve to zero and skipping three steps between each number printed. Below is the result:
12 9 6 3 0
while
and do...while
Both while
and do...while
allows you to keep doing something as long as a given condition is true. The difference between the two is in when the condition gets checked — before or after executing the block of code.
while
will first check the condition to see if it’s true before executing the block of code. If so, it’ll execute the block of code before checking the condition again. This cycle will go on until the condition evaluates to false
.
do...while
will first execute the block of code before checking the condition to see if it’s true. If so, it’ll execute the block before checking again and so on. Basically, the body of do...while
executes at least once regardless of the condition.
The following while
loop executes the code block for as long as x
is less than or equal to 6
:
var x = 1 while (x <= 6) { println("Number $x") ++x }
The result:
Line 1 Line 2 Line 3 Line 4 Line 5 Line 6
The following do...while
loop also executes the code block for as long as x
is less than or equal to 6
. However, it first executes the block before checking the condition:
var x = 1 do{ println("Number $x") ++x } while (x <= 6)
The above code gives the same output as the while
loop example. Before proceeding, there is something important that you should keep in mind.
If you were paying attention, you might have asked the following question: “What if the condition continues to be true
and never evaluates to false
?” The answer is that it leads to a problem known as an infinite loop.
An infinite loop or indefinite loop is one that never ends and goes on infinitely unless an external intervention occurs —  usually, the page starts to freeze and the browser prompts you to close the tab.
When you’re using a loop in your program, you must make sure that the loop has a termination point  —  a point where the condition evaluates to false
. Otherwise, it’ll lead to an infinite loop.
Going back to the last two while
and do...while
loop examples, you can see that we incremented the variable x
on every iteration. This move ensures that the loop gets terminated eventually — in this case, when x
becomes greater than 6
.
Here’s an example of an infinite loop:
var x = 1 while (x <= 6) { println("Number $x") }
This is an infinite loop because x
will always be 1 on every iteration, and therefore, the while
check will always evaluate to true
.
Next, we’ll take a look at ways to control the flow of program execution in a loop.
break
and continue
to control loop executionWhen you’re executing a loop in your Kotlin program, you can use the break
and continue
jump expressions to control the flow of code execution inside the loop.
break
expressionWhen performing a loop in your Kotlin program, the break
expression is used to terminate the loop when a condition becomes true
.
Let’s take a look at the following example. Once we find myLuckyNumber
, it makes no sense to continue iterating over the rest, so we used the break
expression to terminate the loop:
val myLuckyNumber = 5 for (i in 1..10) { if(i == myLuckyNumber) { break } println("Current no is "+ i +". I want to stop at 4") }
Once the for
iteration gets to 5
, it terminates the loop. Here’s the output:
Current no is 1. I want to stop at 4 Current no is 2. I want to stop at 4 Current no is 3. I want to stop at 4 Current no is 4. I want to stop at 4
The break
expression isn’t just used to terminate a loop before its end, but also used to terminate infinite loops. Assuming the loop above was meant to go on forever (and not terminate when i
is equals to 10), using break
as we did in the above example will also terminate the loop.
continue
expressionThe continue
expression is used to skip a particular iteration in a loop.
Let’s take a look at the following example, which is similar to the previous one. This time, we don’t want to iterate over myUnluckyNumber
, so we skip it by using the continue
expression:
val myUnluckyNumber = 3 for (i in 1..10) { if(i == myUnluckyNumber) { continue } println("Current no is "+ i +". I don't want to see number 3, it's bad!") }
Here’s the output:
Current no is 1. I don't want to see number 3, it's bad! Current no is 2. I don't want to see number 3, it's bad! Current no is 4. I don't want to see number 3, it's bad! Current no is 5. I don't want to see number 3, it's bad! Current no is 6. I don't want to see number 3, it's bad! Current no is 7. I don't want to see number 3, it's bad!
Let’s review what we discussed in this article about conditions and loops in the Kotlin programming language.
if
is used to execute a sequence of code if a given condition is true. You can chain an else
block to it and define the code that should be executed if the condition were to be false
.
when
evaluates a condition and sequentially compares the value with any of those in its branches. If there is a match, it’ll run the corresponding code. If there is no match, it’ll fall back to the else
block — which, in that case, must be provided.
A for
loop can be used to iterate through anything that provides an iterator, which could be a string, array, map and so on.
Always ensure that a loop can be terminated to prevent creating an infinite loop. To terminate a loop when a given condition becomes true
, you use the break
expression within an if
check inside the loop.
To skip a particular iteration in a loop when a given condition is true
, you use the continue
expression within an if
check inside the loop.
Thanks for reading, have a great week!
LogRocket is an Android monitoring solution that helps you reproduce issues instantly, prioritize bugs, and understand performance in your Android apps.
LogRocket also helps you increase conversion rates and product usage by showing you exactly how users are interacting with your app. LogRocket's product analytics features surface the reasons why users don't complete a particular flow or don't adopt a new feature.
Start proactively monitoring your Android apps — try LogRocket for free.
Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowReact Native’s New Architecture offers significant performance advantages. In this article, you’ll explore synchronous and asynchronous rendering in React Native through practical use cases.
Build scalable admin dashboards with Filament and Laravel using Form Builder, Notifications, and Actions for clean, interactive panels.
Break down the parts of a URL and explore APIs for working with them in JavaScript, parsing them, building query strings, checking their validity, etc.
In this guide, explore lazy loading and error loading as two techniques for fetching data in React apps.