Describe the control flow statements available in Kotlin, such as if-else, when, and for loops.
Kotlin provides several control flow statements that allow you to control the flow of execution in your code. The main control flow statements in Kotlin include if-else, when, and for loops. Each of these statements serves a specific purpose and offers flexibility in handling different conditions and iterations.
1. if-else Statement:
The if-else statement in Kotlin allows you to conditionally execute blocks of code based on a given condition. It follows the syntax:
```
kotlin`if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}`
```
The if-else statement evaluates the condition and executes the corresponding block of code based on whether the condition is true or false.
Example:
```
kotlin`val age = 25
if (age >= 18) {
println("You are an adult.")
} else {
println("You are not yet an adult.")
}`
```
2. when Expression:
The when expression is Kotlin's enhanced version of the traditional switch statement. It allows you to evaluate an expression and execute different code blocks based on its value. The when expression can handle a variety of conditions, including ranges, types, and custom conditions.
```
kotlin`when (value) {
condition1 -> {
// Code to be executed if condition1 is satisfied
}
condition2 -> {
// Code to be executed if condition2 is satisfied
}
else -> {
// Code to be executed if none of the conditions are satisfied
}
}`
```
The when expression checks the value against each condition and executes the corresponding block of code for the first matching condition. If none of the conditions match, the `else` block (if provided) is executed.
Example:
```
kotlin`val dayOfWeek = 5
when (dayOfWeek) {
1 -> println("Monday")
in 2..5 -> println("Weekday")
in 6..7 -> println("Weekend")
else -> println("Invalid day")
}`
```
3. for Loop:
The for loop in Kotlin is used to iterate over a range, an array, a collection, or any object that provides an iterator. It allows you to execute a block of code repeatedly for each item in the specified range or collection.
```
kotlin`for (item in collection) {
// Code to be executed for each item
}`
```
The `item` variable takes the value of each element in the collection during each iteration of the loop.
Example:
```
kotlin`val numbers = listOf(1, 2, 3, 4, 5)
for (number in numbers) {
println(number)
}`
```
These control flow statements provide flexibility in handling different conditions and iterations in Kotlin. By leveraging if-else statements, when expressions, and for loops, you can make your code more dynamic and responsive to various scenarios.