If-else statement

Reading Time: 2 minutes

Kotlin provides many decision making statements that help the flow of the Kotlin program based on certain logical conditions. The if/else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed. You can use the if statement to specify a block of code to be executed if a condition is true.

If-else

 
Good Morning!

In this example “Good Morning!” will be printed out, because the hour variable is less than 12. What if we need to print another message if hour is not less than 12? The else statement is used to specify a block of code to be executed if the condition evaluates to false.

 
Good Day!

If-else-if

You can chain multiple if-else-if blocks with more conditions.
If one of the else if is true, than the if condition will stopped.

 
a is greater than or equal to 30

Assign values

In Kotlin, if is an expression, i.e. it returns a value.
This means, we can use if to assign values to a variable based on the condition.

 
19

 

Questions

I hope the description was understandable and clear. But if you have still questions, then leave me comments below! 😉

Have a nice a day! 🙂

 


 

Follow and like us:
Click to rate this post!
[Total: 0 Average: 0]

Leave a comment

stay informed!

Subscribe to receive exclusive content and notifications