Explanation of Control Flow in Kotlin
Let's get started.
What is Control Flows in Kotlin?
Control flow structures allow developers to dictate the order of statements of the program for execution. In Kotlin, control flows are concise, expressive and designed to make code safer and more readable.
Conditional Statements in Kotlin
In Kotlin there are two main conditional constructs: if and when.
fun maxOf(a: Int, b: Int): Int {
return if (a > b) a else b
}
In Kotlin there is no ternary operator (statement ? ... : ...) is needed because if expressions serve the same purpose.
val temperature = 28
if (temperature > 30) {
println("It's hot outside.")
} else if (temperature in 20..30) {
println("The weather is pleasant.")
} else {
println("It's cold.")
}
Now lets also make some examples about when expressions
As you can see below when expression is more flexible then java language.fun describe(obj: Any): String =
when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long number"
!is String -> "Not a String"
else -> "Unknown"
}
As you can see above, You can use when without an argument to evaluate conditions directly. So when we use any type we can evalute the data for various aspect.
val number = 15
when {
number % 2 == 0 -> println("Even")
number % 3 == 0 -> println("Divisible by 3")
else -> println("Odd and not divisible by 3")
}
Loops
Kotlin’s primary looping constructs are for, while and do...while.for Loop
Kotlin’s for loop works with ranges, collections, and arrays.
for (i in 1..5) {
println("Number: $i")
}
You can also use ranges with steps or in reverse. For example below loop will count from 10 to 1 by 2 and print them.
for (i in 10 downTo 1 step 2) {
println(i)
}
val fruits = listOf("Apple", "Banana", "Cherry")
for (fruit in fruits) {
println(fruit)
}
val fruits = listOf("Apple", "Banana", "Cherry")
for ((index, fruit) in fruits.withIndex()) {
println("$index: $fruit")
}
while and do...while
while checks the condition before entering the loop, while do...while checks it after the body executes once like the other programming languages.
var x = 5
while (x > 0) {
println(x)
x--
}
var count = 0
do {
println("Count: $count")
count++
} while (count < 3)
Jump Expressions
Kotlin also provides break, continue and return to control the flow within loops and functions like other programming languages.
break and continue
These behave similarly to other C-style languages.
for (i in 1..10) {
if (i == 3) continue // Skip iteration for i = 3
if (i == 7) break // Exit loop when i = 7
println(i)
}
Labels in Kotlin
Kotlin also has a feature to label the loops and control expressions precisely with @label. So with this we can break also outer labeled loops.
Here is the example of usage of labels in Kotlin
outer@ for (i in 1..3) {
for (j in 1..3) {
if (i == 2 && j == 2) break@outer
println("i = $i, j = $j")
}
}
Here, break@outer also stops the outer loop together with inner loop.
return in Lambdas
When working with hierarchical lambda expressions, when we use return it normally exit the nearest expression. With the help of labels we can control it.
fun main() {
listOf(1, 2, 3, 4).forEach {
if (it == 3) return@forEach
println(it)
}
println("Done with loop.")
}
Here, return@forEach skips the element 3 instead of exiting the entire main function.
Table of Control Flow keywords in Kotlin
| Keyword | Description | Typical Use |
|---|---|---|
| if | Conditional expression | Choose between two or more values |
| when | Pattern matching control structure | Replace switch, handle multiple conditions |
| for | Iteration over ranges or collections | Loop through data |
| while, do...while | Conditional loops | Repeat until a condition changes |
| break, continue, return, @label | Jump and flow control | Fine-grained loop control |
That is all.
Burak Hamdi TUFAN