Kotlin has the familiar if-else
statement that you are used to from Java and
Python:
i = 10
if (i < 11):
print("Here")
else:
print("There")
Kotlin does not have a switch statement, but instead has a more powerful
conditional called when
:
Without an argument when
can be used to replace simple if-else
chains:
In this last form each conditional expression on the left side of each statement
in when when
block is evaluated until we find one that is true, or reach the
else
statement.
Unlike Java or Python (or JavaScript), both if-else
and when
can be used in
Kotlin as expressions—used to assign variables.
This proves to be quite natural and elegant:
Note how the example above allows us to preserve both the immutability and
non-nullability of the variable grade
.
There is no way to accomplish this in either Java or Python.
Again, since grade
would need to be declared outside of the block but set
inside, it would have to be mutable.
When using if-else
as an expression the last statement from each block is used
to perform the assignment.
But each branch of the if-else
can also do other work—it doesn’t just
have to return a value.
Finally, whenever we use a conditional expression to set a variable, Kotlin will
help ensure that the variable does get set by requiring an else
statement: