Kotlin is an expressive programming language that simplifies common coding tasks. One fundamental concept you need to master in Kotlin is control flow. Control flow statements allow you to govern the execution path of your code.
Table of Contents
If-Else Statements
The if-else statement is a fundamental control flow statement that executes some code if a particular condition is true, and possibly different code if it is not.
val number = 5
if (number > 0) {
println("Number is positive")
} else {
println("Number is negative or zero")
}You can also use if as an expression:
val result = if (number % 2 == 0) "Even" else "Odd"
println(result)When Statements
The 'when' statement in Kotlin is similar to the switch-case statement in other languages. It is more powerful and can be used as both a statement and an expression.
val day = "Monday"
when (day) {
"Monday", "Tuesday", "Wednesday", "Thursday", "Friday" -> println("Weekday")
"Saturday", "Sunday" -> println("Weekend")
else -> println("Not a valid day")
}When is also used as an expression:
val response = when (number) {
in 0..10 -> "Single-digit"
!in 0..10 -> "Multiple-digits"
else -> "None"
}
println(response)For Loops
Kotlin offers a variety of looping constructions. The for loop is commonly used to iterate over ranges, arrays, or other iterable objects.
for (i in 1..5) {
println(i)
}You can also traverse arrays:
val array = arrayOf(1, 2, 3, 4, 5)
for (i in array) {
println(i)
}While Loops
The while loop repeats a block of code as long as a specified condition is true.
var x = 0
while (x < 5) {
println(x)
x++
}A do-while loop is similar to a while loop but checks the condition after executing the code block, ensuring the code block is run at least once.
var y = 0
do {
println(y)
y++
} while (y < 5)These control flow constructs provide foundational skills for programming in Kotlin, enabling you to create more sophisticated logic and handle complex problems effectively.