Control flow statements are essential for directing the execution of your Kotlin programs. They allow you to make decisions, execute code repeatedly, and handle different conditions based on runtime values. This section will cover the fundamental control flow statements available in Kotlin: if expressions, when expressions, loops (for and while), and jump statements (break, continue, and return). By understanding these concepts, you'll be able to write more efficient and readable Kotlin code.
The if expression is used for conditional branching in Kotlin. It evaluates a boolean condition and executes the corresponding block of code based on whether the condition is true or false.
val number = 10
if (number > 5) {
println("Number is greater than 5")
} else {
println("Number is not greater than 5")
}
In this example, since number is indeed greater than 5, the output will be "Number is greater than 5".
Kotlin's if can also act as an expression, returning a value. This makes it versatile and often used in place of ternary operators found in other languages.
val max = if (a > b) a else b
Here, the max variable will hold the greater value between a and b.
You can use multiple else if branches to handle more complex conditions:
val grade = 85
var result: String
if (grade >= 90) {
result = "A"
} else if (grade >= 80) {
result = "B"
} else if (grade >= 70) {
result = "C"
} else {
result = "F"
}
println("Grade: $result")
This code assigns a letter grade based on the grade variable.
if expressions as expressions when possible to make your code more concise and functional.if statements; consider using early returns or restructuring logic to improve readability.The when expression is a powerful alternative to multiple if-else statements. It's similar to the switch statement in other languages but more flexible and expressive.
val number = 2
when (number) {
1 -> println("One")
2 -> println("Two")
else -> println("Other")
}
In this example, since number is 2, the output will be "Two".
You can combine multiple conditions in a single branch using commas:
val letterGrade = 'B'
when (letterGrade) {
'A', 'B', 'C' -> println("Pass")
else -> println("Fail")
}
This code will print "Pass" for grades A, B, or C.
when can also check if a value is within a range or part of a collection:
val age = 25
when (age) {
in 1..18 -> println("Minor")
in 19..60 -> println("Adult")
else -> println("Senior")
}
val list = listOf(1, 2, 3)
when {
1 in list -> println("One is in the list")
else -> println("One is not in the list")
}
Like if, when can also be used as an expression:
val result = when (number) {
1 -> "One"
2 -> "Two"
else -> "Other"
}
println("Result: $result")
This will assign the string value to result.
when for more than two conditions to improve readability over multiple if-else statements.else branch to handle unexpected cases.Kotlin provides two types of loops: for and while. These are used to execute a block of code repeatedly under certain conditions.
The for loop is used for iterating over collections, arrays, ranges, or any other iterable objects.
val fruits = listOf("Apple", "Banana", "Cherry")
for (fruit in fruits) {
println(fruit)
}
This will print each fruit in the list.
for (i in 1..5) {
println(i)
}
This loop prints numbers from 1 to 5.
indices and withIndexYou can access indices or iterate with index using indices and withIndex:
val array = arrayOf("A", "B", "C")
for (index in array.indices) {
println("Index: $index, Value: ${array[index]}")
}
for ((index, value) in array.withIndex()) {
println("Index: $index, Value: $value")
}
The while loop executes as long as a specified condition is true.
var count = 0
while (count < 5) {
println(count)
count++
}
This will print numbers from 0 to 4.
Kotlin does not have a built-in do-while loop, but you can simulate it using a while loop:
var i = 0
do {
println(i)
i++
} while (i < 5)
This will also print numbers from 0 to 4.
for loops for iterating over collections or ranges.while loops when the number of iterations is not known beforehand.Jump statements allow you to alter the normal flow of execution in a loop. Kotlin provides three jump statements: break, continue, and return.
The break statement exits the current loop or switch expression.
for (i in 1..10) {
if (i == 5) break
println(i)
}
This will print numbers from 1 to 4 and then exit the loop.
The continue statement skips the rest of the current iteration and proceeds with the next one.
for (i in 1..10) {
if (i % 2 == 0) continue
println(i)
}
This will print only odd numbers from 1 to 10.
The return statement exits a function and optionally returns a value. It can be used inside loops as well.
fun findFirstEven(numbers: List<Int>): Int? {
for (number in numbers) {
if (number % 2 == 0) return number
}
return null
}
This function returns the first even number from the list or null if no even number is found.
break and continue sparingly to avoid making your code difficult to follow.return statements are used appropriately to maintain clear function logic.Control flow statements in Kotlin provide a robust framework for managing program execution based on conditions. By mastering if, when, loops, and jump statements, you'll be able to write efficient and readable Kotlin code. Remember to apply best practices to keep your code clean and maintainable.