Kotlin If else
Conditional statements in programming are crucial for decision-based systems. These provide a way to execute a particular set of instructions only if a certain condition is true. In Kotlin, the if-else statement is a fundamental construct that enables programmers to create logical branches in their code. Whether it's handling different scenarios, validating input, or determining the flow of execution, if-else plays a pivotal role in controlling the program's behavior.
Kotlin If
The If in Kotlin is an expression, it returns a boolean value true or false based on the expression. It can be used to check some conditions and perform actions based on the evaluation of the condition.
Syntax of If in Kotlin
Example
Let us check if you are eligible to vote or not considering your age. We will take the age variable to store the age of the user. Inside the main function, we have an age variable and an if condition which checks for eligibility and prints a message if the user is eligible.
Code:
Output:
More than one ifs is also allowed in a program. Have a look at the example below:
Code:
Output:
We are using multiple if statements to check against various ranges of temperatures.
Kotlin Else
Only if most of the time sounds incomplete and you must have always heard if-else together. As in the above case what to do if the user is not eligible? Add another if to check so. Print message for all? or print no message at all?
The else statement allows you to execute at least something in case the if statement condition fails. So either the action mentioned in the if is executed or the else block is executed. Both are not executed together.
Syntax
Example
Let us see if the given number is even or odd using if-else statements. It is certain that if the number is not even it is odd. So, the if statement will help us identify if the number is even or not otherwise, we will execute the else statement.
Code:
Kotlin else if
Take an example of the grading system. We require more than 2 grades and thus, more than 2 conditionals. If we place multiple ifs conditions for each if will be checked irrespective of the above conditions being true or false. This is not desired considering the complexity of the programs and performance issues.
We require that check for the conditions from the beginning, if any one condition is satisfied execute that block and come out of the conditional.
The else if supports this methodology and thus for multiple conditions out of which only one can be true we use else if in-between if and else blocks.
Syntax for else if
If none of the conditions result in true then the else block is executed. It acts as a default for most of the cases.
Example of else if
We will take the example of getting the season's name from the month number. Here we are taking three possibilities "Winter", "Summer" or "Monsoon". Note how the else if lets us check three conditions in the same flow. Similarly, we can use more else-ifs to check more than 3 conditions.
Code:
Output:
Kotlin if-else Flow Chart
Let us look at flow charts for the above 3 cases to understand if and else conditionals better.
Flow Chart for if
The chart shows that if the condition is true one additional block of code is executed in case of if.
Flow Chart for if-else
The if-else graph perfectly depicts that in case the if condition returns true, the if block is executed otherwise the else block is executed.
Flow Chart for if-else-if
The if-else-if ladder shows that multiple conditions are checked and if any one of them is satisfied then we exit out of the conditional block.
Kotlin if-else Expression as Ternary Operator
Unlike other programming languages like Java or C++, Kotlin doesn't have a ternary operator (? :).
The ternary operator is usually used for value assignments. If the given condition is true, it will assign the value before : else will assign the value after the : colon. It is called inline conditional as the condition is checked within the single line of code.
Kotlin programming language encourages the use of if-else statements only for inline condition checking.
Syntax for if-else Expression as Ternary Operator
Example
To check if the number is positive or negative, we can use the inline if-else expression as follows:
Code:
Output:
Kotlin if-else-if Ladder Expression
The if-else-if with multiple else ifs is also called the if-else-if ladder. This is because when we see them in the code it looks like a ladder.
Often we are to check against lots of conditions out of which only one is true. This leaves us with the option of using the if-else-if ladder.
From the very first if statement, each of the conditions is evaluated and checked if true one by one. If any of these conditions are found to be true no further checks are required.
The block with the evaluation as true is executed and we exit from the entire block. If none of the conditions are evaluated to be true then the last else is executed.
Syntax for if-else-if Ladder
Let us take the example of a good old grading system with marks of various students.
Code:
Output:
Now for the above example, the first if condition is checked which returns false. The next condition in the second block is checked. This evaluates to true and thus is executed. Next, we come out of all the if-else and execute the rest of the program.
Let us say the score was 40, in this case, all the if conditionals will be checked. Only the last else-if will result in true and hence will be executed.
Use Cases with Examples
Let's consider a practical use case for an online shopping application. Imagine you have a scenario where you want to calculate and apply discounts based on the total purchase amount. Here's a simplified example:
Code:
Output:
In this example:
- The if-else statement determines the discount rate based on the totalAmount.
- If the totalAmount is greater than or equal to 100, a 10% discount is applied.
- If the total amount is less than 100, a 5% discount is applied.
- The discounted amount is then calculated based on the discount rate.
This is a practical use case where if-else statements are used to make decisions and apply different logic based on a condition, such as calculating discounts in an e-commerce application.
Conclusion
- Kotlin if else lets us write conditional code. A block of code or instructions is only executed if a certain condition is satisfied.
- The single if is useful if we only have one block to be executed if the condition is true.
- The if-else statement is used if we have two options out of which only one should be executed.
- The if-else-if ladder is useful for the cases where we are supposed to check against multiple cases out of which only one should be executed.