Kotlin has the familiar
if-else statement that you are used to from Java and
i = 10 if (i < 11): print("Here") else: print("There")
Kotlin does not have a switch statement, but instead has a more powerful
Without an argument
when can be used to replace simple
In this last form each conditional expression on the left side of each statement
when block is evaluated until we find one that is true, or reach the
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
There is no way to accomplish this in either Java or Python.
grade would need to be declared outside of the block but set
inside, it would have to be mutable.
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