Kotlin Conditional Statements If-statement as an expression


Example

If-statements can be expressions:

val str = if (condition) "Condition met!" else "Condition not met!"

Note that the else-branch is not optional if the if-statement is used as an expression.

This can also been done with a multi-line variant with curly brackets and multiple else if statements.

val str = if (condition1){
    "Condition1 met!" 
   } else if (condition2) {
    "Condition2 met!" 
   } else {
    "Conditions not met!"
   }

TIP: Kotlin can infer the type of the variable for you but if you want to be sure of the type just annotate it on the variable like: val str: String = this will enforce the type and will make it easier to read.