If-statement as an expression
suggest changeIf-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 be done with a multi-line form, curly braces, and multiple else if branches.
val str = if (condition1){
"Condition1 met!"
} else if (condition2) {
"Condition2 met!"
} else {
"Conditions not met!"
}
TIP: Kotlin can infer the variable’s type. If you want to be sure, annotate it:
val str: String = .... That enforces the type and makes the code easier to read.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents