Conditional Statements


Conditional Statements

Conditional statements are statements used in decision-making. These statements determine which code should be executed when the condition is true and when the condition is false.

Kotlin has the following conditions:

cda3dr kjhgfdsaasdfghj

  • If a particular condition is true, use if to specify a block of code to be executed.
  • If the same condition is incorrect, use another to specify one block of code to be executed.
  • If the same condition is incorrect, use another to specify one block of code to be executed.
  • Use when to specify multiple alternative blocks of code to be executed.

Note: Unlike Java, if..else can be used as a statement or an expression (to assign a value to a variable) in Kotlin. See an example at the bottom of the page to better understand this.

Kotlin Conditional Statements

The following are the types of conditional statements in Kotlin:

  • if statement
  • if-else statement
  • if-else as expression
  • when statement

If Statement

If statement first checks the condition and if the condition is true, the code below if statements will be executed. If the condition can be used as an expression in Kotlin, a value can be returned to it.

If-else Statement

If statement condition allows executing the code only if the condition is true, but what if the condition is false. In this case, we need another statement called else; the other block of code will be executed only if the condition is false.

If-else as Expression

The if-else statement acts as an expression, especially like the ternary operator. If the condition is true, it will give the first value, and if the condition is false, it will give another result.

When Statement

When multiple choices are there, we can use when statements instead of multiple if..else..if statements.

It replaces the switch block, i.e., In C or Java, functions similar to the switch block but with better performance.

Note: No break statement is required as the block automatically dismisses the statements after being executed in the matching test condition.