If, Else statement
val age = 20
if (age >= 18) {
println("Welcome to KtDevLog!")
} else {
println("Sorry, you are too young.")
}KtDevlogImagine, on your apps have many users you want to add filter or logic for allowing the access. So you think you only access the if the user age 18 or above 18. Then your can used this statement. if statement used for comparison. And else statement executes a block of code only when the preceding if condition is false.
when
Imagine you are at a vending machine. You press a number, and the machine “matches” that number to a specific snack. That is exactly what when does.
val dayNumber = 3
val dayName = when (dayNumber) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
else -> "Other day" // The 'else' acts like a fallback
}
println(dayName) // Output: WednesdayKtDevlogComparison: if-else vs when
| Feature | if-else | when |
| Readability | Becomes messy with many conditions. | Very clean and organized. |
| Logic | Best for True/False decisions. | Best for multiple choice options. |
| Flexibility | Standard logic. | Can check types, ranges, and conditions. |






