Conditions and Loops
if expression
In Kotlin, if is an expression: it returns a value.
Branches of an if expression can be blocks. In this case, the last expression is the value of a block:
when expression
when defines a conditional expression with multiple branches.
It is similar to the switch statement in C-like languages.
when matches its argument against all branches sequentially until some branch condition is satisfied.
when can be used either as an expression or as a statement.
If it is used as an expression, the value of the first matching branch becomes the value of the overall expression.
If it is used as a statement, the values of individual branches are ignored.
The else branch is evaluated if none of the other branch conditions are satisfied.
In when statements, the else branch is mandatory in the given condition:
whenhas a subject of aBoolean,enum, orsealedtype, or their nullable counterpartsand branches of
whendon't cover all possible cases for this subject.
To define a common behavior for multiple cases, combine their conditions in a single line with a comma:
You can use arbitrary expressions (not only constants) as branch conditions
You can also check a value for being in or !in a range or a collection:
Another option is checking that a value is or !is of a particular type.
when can also be used as a replacement for an if-else if chain.
If no argument is supplied, the branch conditions are simply boolean expressions, and a branch is executed when its condition is true:
You can capture when subject in a variable using following syntax:
The scope of variable introduced in when subject is restricted to the body of this when.
for Loops
The for loop iterates through anything that provides an iterator.
A for loop over a range or an array is compiled to an index-based loop that does not create an iterator object.
If you want to iterate through an array or a list with an index, you can do it this way:
Alternatively, you can use the withIndex library function: