val str = "Hello!"
if (str.length == 0) {
print("The string is empty!")
} else if (str.length > 5) {
print("The string is short!")
} else {
print("The string is long!")
}
The else-branches are optional in normal if-statements.
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 el...
The when-statement is an alternative to an if-statement with multiple else-if-branches:
when {
str.length == 0 -> print("The string is empty!")
str.length > 5 -> print("The string is short!")
else -> print("The string is long!")
...
When given an argument, the when-statement matches the argument against the branches in sequence. The matching is done using the == operator which performs null checks and compares the operands using the equals function. The first matching one will be executed.
when (x) {
"English" -...
Like if, when can also be used as an expression:
val greeting = when (x) {
"English" -> "How are you?"
"German" -> "Wie geht es dir?"
else -> "I don't know that language yet :("
}
print(greeting)
To be used as an express...
when can be used to match enum values:
enum class Day {
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
fun doOnDay(day: Day) {
when(day) {
Day.Sunday -> // Do something
Day.Monday, Day.Tuesday -> // Do oth...