Kotlin If Else
Kotlin If Else is a decision making statement, that can be used to execute one of the two code blocks based on the result of a condition.
In this tutorial, you can learn the syntax of if-else statement, and understand how to write if-else statements in a Kotlin program with examples.
Syntax
The syntax of if else statement in Kotlin is as shown in the following.
if(condition) {
//if-block statement(s)
} else {
//else-block statement(s)
}
- if, else: Kotlin keywords.
- condition: a boolean expression or something that evaluates to a boolean value.
- () encloses condition, and {} encloses code blocks.
If the condition evaluates to true, runtime executes corresponding if-block statement(s).
If the condition evaluates to false, runtime executes corresponding else-block statement(s).
else block is optional. So, if-else without else would become a simple if statement in Kotlin.
Examples
1. Check if number is even or odd using if-else
In the following program, we check if the given number is even number or odd number using an if-else statement, and print the output.
Main.kt
fun main(args: Array<String>) {
val a = 13
if(a%2==0) {
print("$a is even number.")
} else {
print("$a is odd number.")
}
}
Output
13 is odd number.
Since a=13
is odd, a%2==0
evaluates to false. So, the else block is executed.
2. If-else optional braces
Braces are optional if the number of statements in the corresponding block is one.
In the following example, we have only one statement in if and else blocks. So, the braces are optional for both the if and else blocks. Hence no braces.
Though braces are optional, it is recommended to use braces to enclose if or else code blocks to enhance the readability of the program.
Main.kt
fun main(args: Array<String>) {
val a = 15
if(a%2==0)
print("$a is even number.")
else
print("$a is odd number.")
}
Output
15 is odd number.
Nested If Else
We can nest an if-else statement inside another if-else statement. When we say if-else in this context, it could be simple if statement, or if-else statement or if-else-if statement.
In the following example, we have written an if-else-if statement inside a simple if statement.
Main.kt
fun main(args: Array<String>) {
val a = 6
if(a%2==0) {
println("$a is even number.")
if(a%5==0) {
println("$a is divisible by 5.")
} else if(a%3==0) {
println("$a is divisible by 3.")
}
}
}
Run the program.
Output
6 is even number.
6 is divisible by 3.
if-else-if statement inside if statement is like any other Kotlin statement. So, the if the execution enters inside the if statement, if-else-if shall be executed like we have seen in the previous examples.
Conclusion
Concluding this Kotlin Tutorial, we learned what if-else statement is and its variations in Kotlin programming language.