In Kotlin, if is an expression, i.e. it returns a value. Therefore there is not ternary operator (condition ? then : else), because ordinary if works fine in this role. Consider the following examples:
If branches can be blocks, and the last expression is the value of a block:
See the grammar for if here.
When replaces the switch operator of C-like languages. In the simplest form it looks like this:
When matches its argument against all branches consequently until some branch condition is satisfied. When is an expression and results in satisfied branch's right hand side. If some of its branches return result in a value of type Unit, the whole expression has type Unit.
Note that the else branch is mandatory, unless the compiler can prove that all possible cases are covered with branch conditions.
If many cases should be handled in the same way, the branch conditions may be combined with a comma:
We can use arbitrary expressions (not only constants) as branch conditions:
One can also check a value for being in or !in a range:
Inside when expressions, continue jumps to the next branch condition, if any:
This mechanism replaces the concept of guards available in other languages. I.e. in Scala one has guard if expressions in match (that corresponds to when):
This can be rewritten in Kotlin with as follows:
See Returns and jumps for more information about continue.
See the grammar for when here.
|Continue in when is not implemented yet|
See the corresponding issue
For loop iterates through anything that provides an iterator. The syntax is as follows:
The body can be a block.
As mentioned before, for iterates through anything that provides and iterator, i.e.
- has an instance- or extension-function iterator(), whose return type
- has an instance- or extension-function next(), and
- has an instance- or extension-function hasNext() that returns Boolean.
If you want to iterate through an array or list with an index, you can do it this way:
Note that this "iteration through a range" is compiled down to optimal implementation with no extra objects created.
See the grammar for for here.
While and do..while work as usual:
See the grammar for while here.
See Exceptions for the details.