In this tutorial, we will focus on how to use conditional statements effectively in Kotlin. This includes understanding the use of 'if' and 'when' statements to control the flow of your program based on different conditions.
What will you learn:
Prerequisites:
In programming, conditional statements are used to perform different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false.
In Kotlin, the structure of an 'if' statement is pretty simple:
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
'when' is another conditional statement in Kotlin that can be used as an alternative to 'if-else-if' ladders or switches. It is concise and more readable.
when (variable) {
case1 -> // code to be executed if variable matches case1
case2 -> // code to be executed if variable matches case2
else -> // code to be executed if variable doesn't match any case
}
val number = 10
if (number > 0) {
println("The number is positive")
} else {
println("The number is not positive")
}
Output:
The number is positive
This code checks if the given number is greater than 0. If it is, it prints "The number is positive"; otherwise, it prints "The number is not positive".
val grade = 'A'
when (grade) {
'A' -> println("Excellent!")
'B', 'C' -> println("Well done")
'D' -> println("You passed")
else -> println("Invalid grade")
}
Output:
Excellent!
This code checks the value of grade. If it's 'A', it prints "Excellent!", if it's 'B' or 'C' it prints "Well done", if it's 'D' it prints "You passed", and for any other value, it prints "Invalid grade".
In this tutorial, we learned about the use of conditional statements in Kotlin. We covered 'if' and 'when' statements with clear, practical examples. As next steps, you can explore more about Kotlin loops and functions.
Exercise 1: Write a program in Kotlin to check if a number is even or odd.
Exercise 2: Write a program in Kotlin that uses a 'when' statement to determine the day of the week based on a number (1-7).
Exercise 3: Modify the above program to include an 'else' clause for invalid inputs.
Solutions and explanations will be provided in the next tutorial. Keep practicing!