In this article, You’ll learn how to use Kotlin’s control flow expressions and statements which includes conditional expressions like if
, if-else
, when
and looping statements like for
, while
, and do-while
.
If Statement
The If
statement allows you to specify a section of code that is executed only if a given condition is true-
var n = 34
if(n % 2 == 0) {
println("$n is even")
}
// Displays - "34 is even"
The curly braces are optional if the body of if
statement contains a single line -
if(n % 2 == 0) println("$n is even")
If-Else Statement
The if-else
statement executes one section of code if the condition is true and the other if the condition is false -
var a = 32
var b = 55
if(a > b) {
println("max($a, $b) = $a")
} else {
println("max($a, $b) = $b")
}
// Displays - "max(32, 55) = 55"
Using If as an Expression
In Kotlin, You can use if
as an expression instead of a statement. For example, you can assign the result of an if-else
expression to a variable.
Let’s rewrite the if-else
example of finding the maximum of two numbers that we saw in the previous section as an expression -
var a = 32
var b = 55
var max = if(a > b) a else b
println("max($a, $b) = $max")
// Displays - "max(32, 55) = 55"
Note that when you’re using if
as an expression, it is required to have an else
branch, otherwise, the compiler will throw an error.
The if-else
branches can also have block bodies. In case of block bodies, the last expression is the value of the block -
var a = 32
var b = 55
var max = if(a > b) {
println("$a is greater than $b")
a
} else {
println("$a is less than or equal to $b")
b
}
println("max($a, $b) = $max")
# Output
32 is less than or equal to 55
max(32, 55) = 55
Unlike Java, Kotlin doesn’t have a ternary operator because we can easily achieve what ternary operator does, using an if-else
expression.
If-Else-If Chain
You can chain multiple if-else-if
blocks like this -
var age = 17
if(age < 12) {
println("Child")
} else if (age in 12..17) {
println("Teen")
} else if (age in 18..21) {
println("Young Adult")
} else if (age in 22..30) {
println("Adult")
} else if (age in 30..50) {
println("Middle Aged")
} else {
println("Old")
}
// Displays - "Teen"
In the next section, we’ll learn how to represent if-else-if
chain using a when
expression to make it more concise.
When Expression
Kotlin’s when
expression is the replacement of switch
statement from other languages like C, C++, and Java. It is concise and more powerful than switch
statements.
Here is how a when
expression looks like -
var dayOfWeek = 4
when(dayOfWeek) {
1 -> println("Monday")
2 -> println("Tuesday")
3 -> println("Wednesday")
4 -> println("Thursday")
5 -> println("Friday")
6 -> println("Saturday")
7 -> println("Sunday")
else -> println("Invalid Day")
}
// Displays - "Thursday"
when
expression matches the supplied argument with all the branches one by one until a match is found. Once a match is found, it executes the matched branch. If none of the branches match, the else
branch is executed.
In the above example, all the branches contain a single statement. But they can also contain multiple statements enclosed in a block -
var dayOfWeek = 1
when(dayOfWeek) {
1 -> {
// Block
println("Monday")
println("First day of the week")
}
7 -> println("Sunday")
else -> println("Other days")
}
Using when
as an expression
Just like if
, when
can be used as an expression and we can assign its result to a variable like so -
var dayOfWeek = 4
var dayOfWeekInString = when(dayOfWeek) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6 -> "Saturday"
7 -> "Sunday"
else -> "Invalid Day"
}
println("Today is $dayOfWeekInString") // Today is Thursday
Combining multiple when
branches into one using comma
You can combine multiple branches into one using comma. This is helpful when you need to run a common logic for multiple cases -
var dayOfWeek = 6
when(dayOfWeek) {
1, 2, 3, 4, 5 -> println("Weekday")
6, 7 -> println("Weekend")
else -> println("Invalid Day")
}
// Displays - Weekend
Checking whether a given value is in a range or not using in
operator
A range
is created using the ..
operator. For example, you can create a range from 1 to 10 using 1..10
. You’ll learn more about range
in a future article.
The in
operator allows you to check if a value belongs to a range/collection -
var dayOfMonth = 5
when(dayOfMonth) {
in 1..7 -> println("We're in the first Week of the Month")
!in 15..21 -> println("We're not in the third week of the Month")
else -> println("none of the above")
}
// Displays - We're in the first Week of the Month
Checking whether a given variable is of certain type or not using is
operator
var x : Any = 6.86
when(x) {
is Int -> println("$x is an Int")
is String -> println("$x is a String")
!is Double -> println("$x is not Double")
else -> println("none of the above")
}
// Displays - none of the above
Using when
as a replacement for an if-else-if
chain
var number = 20
when {
number < 0 -> println("$number is less than zero")
number % 2 == 0 -> println("$number is even")
number > 100 -> println("$number is greater than 100")
else -> println("None of the above")
}
// Displays - 20 is even
While Loop
While loop executes a block of code repeatedly as long as a given condition is true -
while(condition) {
// code to be executed
}
Here is an example -
var x = 1
while(x <= 5) {
println("$x ")
x++
}
// Displays - 1 2 3 4 5
In the above example, we increment the value of x by 1 in each iteration. When x reaches 6, the condition evaluates to false and the loop terminates.
do-while loop
The do-while
loop is similar to while
loop except that it tests the condition at the end of the loop.
var x = 1
do {
print("$x ")
x++
} while(x <= 5)
// Displays - 1 2 3 4 5
Since do-while
loop tests the condition at the end of the loop. It is executed at least once -
var x = 6
do {
print("$x ")
x++
} while(x <= 5)
// Displays - 6
For Loop
A for-loop is used to iterate through ranges, arrays, collections, or anything that provides an iterator (You’ll learn about iterator in a future article).
Iterating through a range
for(value in 1..10) {
print("$value ")
}
// Displays - 1 2 3 4 5 6 7 8 9 10
Iterating through an array
var primeNumbers = intArrayOf(2, 3, 5, 7, 11)
for(number in primeNumbers) {
print("$number ")
}
// Displays - 2, 3, 5, 7, 11
Iterating through an array using its indices
Every array in Kotlin has a property called indices
which returns a range of valid indices of that array.
You can iterate over the indices of the array and retrieve each array element using its index like so -
var primeNumbers = intArrayOf(2, 3, 5, 7, 11)
for(index in primeNumbers.indices) {
println("PrimeNumber(${index+1}): ${primeNumbers[index]}")
}
# Output
PrimeNumber(1): 2
PrimeNumber(2): 3
PrimeNumber(3): 5
PrimeNumber(4): 7
PrimeNumber(5): 11
Iterating through an array using withIndex()
You can use the withIndex()
function on arrays to obtain an iterable of IndexedValue
type. This allows you to access both the index and the corresponding array element in each iteration -
var primeNumbers = intArrayOf(2, 3, 5, 7, 11)
for((index, number) in primeNumbers.withIndex()) {
println("PrimeNumber(${index+1}): $number")
}
The output of this snippet is same as the previous snippet.
Break and Continue
Break out of a loop using the break
keyword
for (num in 1..100) {
if (num%3 == 0 && num%5 == 0) {
println("First positive no divisible by both 3 and 5: ${num}")
break
}
}
# Output
First positive no divisible by both 3 and 5: 15
Skip to the next iteration of a loop using the continue
keyword
for (num in 1..10) {
if (num%2 == 0) {
continue;
}
print("${num} ")
}
# Output
1 3 5 7 9
Conclusion
That’s all folks! In this article, you learned how to use Kotlin’s conditional expressions like if
, if-else
, when
, and looping statements like for
, while
and do-while
. You can find more articles from the sidebar menu.