Control Flow in Kotlin - If, Else, and When Statements
Control flow statements in Kotlin are essential for decision-making and branching in your code. They allow you to control the execution of your program based on conditions. In this guide, we'll explore the usage of if, else, and when statements in Kotlin.
If Statement
The if statement is used to execute a block of code if a given condition is true:
val age = 25
if (age >= 18) {
println("You are an adult.")
} else {
println("You are not yet an adult.")
}
Else-If Ladder
You can use an else-if ladder to handle multiple conditions:
val grade = 85
if (grade >= 90) {
println("A")
} else if (grade >= 80) {
println("B")
} else if (grade >= 70) {
println("C")
} else {
println("D")
}
When Statement
The when statement is a powerful replacement for switch statements in other languages. It allows you to check multiple conditions succinctly:
val dayOfWeek = "Monday"
when (dayOfWeek) {
"Monday" -> println("It's the start of the workweek.")
"Friday" -> println("It's almost the weekend!")
else -> println("It's a regular day.")
}
Conclusion
Control flow statements like if, else, and when are essential tools for making decisions in your Kotlin code. They allow your programs to respond dynamically to different conditions, enabling you to create versatile and powerful applications. As you explore Kotlin further, you'll find these statements to be vital in your coding journey.
Happy coding!