Control flow
Kotlin has statements for determining what sections of the code will be executed next, during the runtime of a program. These statements are known as control flow statements.
These statments are:
- If-else
- When
- Loops
- for loops
- while loops
- do-while loops
if-else
Kotlin’s if-else
statements are expressions, not keywords. Which means they can have a value. Consider this example where an if-else expression is used to initialize a variable:
val str: String = if (num < 10) "Lower than 10" else "Equal or greater than 10"
When
Kotlin doesn’t have switch statements, like Java and other popular languages. Switch in other languages is a conditional operator which can be used for comparing multiple conditions on a variable.
In Kotlin this operator is called when
and does the same job as a switch in other languages.
It checks the variable value against multiple conditions, and, if a condition is satisfied, it executes the expression for that branch. when
is a lot more powerful than Java’s switch operator...