Mastering Conditions and Loops in Kotlin
Kotlin is a modern programming language that offers a concise and expressive way to write code. In this article, we’ll explore the foundational concepts of conditions and loops in Kotlin, which are essential for any aspiring developer.
Understanding Conditions
Conditions are used to execute a block of code based on a specific criteria. In Kotlin, we use if
and when
expressions to evaluate conditions.
If Expression
The if
expression is used to execute a block of code if a condition is true. We can also use an optional else
block to specify an alternative action.
kotlin
val num = 10
if (num > 5) {
println("Number is greater than 5")
} else {
println("Number is less than or equal to 5")
}
When Expression
The when
expression is used to evaluate a condition and execute a corresponding block of code. We can specify multiple branches using the when
keyword.
kotlin
val day = 1
when (day) {
1 -> println("Monday")
2 -> println("Tuesday")
3 -> println("Wednesday")
else -> println("Invalid day")
}
Understanding Loops
Loops are used to execute a block of code repeatedly until a condition is met. In Kotlin, we have three types of loops: for
, while
, and do-while
.
For Loop
The for
loop is used to iterate over a collection or a range of values.
kotlin
val numbers = listOf(1, 2, 3, 4, 5)
for (num in numbers) {
println(num)
}
While Loop
The while
loop is used to execute a block of code while a condition is true.
kotlin
var i = 0
while (i < 5) {
println(i)
i++
}
Do-While Loop
The do-while
loop is used to execute a block of code at least once, and then continue executing while a condition is true.
kotlin
var i = 0
do {
println(i)
i++
} while (i < 5)
Controlling Loop Execution
We can use break
and continue
expressions to control the execution of loops.
Break Expression
The break
expression is used to exit a loop immediately.
kotlin
for (i in 1..5) {
if (i == 3) break
println(i)
}
Continue Expression
The continue
expression is used to skip the current iteration and move to the next one.
kotlin
for (i in 1..5) {
if (i == 3) continue
println(i)
}
In conclusion, mastering conditions and loops is essential for any aspiring Kotlin developer. By understanding how to use if
and when
expressions, as well as for
, while
, and do-while
loops, you’ll be able to write more efficient and effective code. Remember to use break
and continue
expressions to control the execution of loops and make your code more robust.