Kotlin has many control flow elements known from Java, but they offer a little bit more flexibility and in some cases their usage is simplified. Kotlin introduces a new control flow construct known as when
as a replacement for Java's switch... case
.
At its core, Kotlin's if
clause works the same way as in Java:
val x = 5 if(x > 10){ println("greater") } else { println("smaller") }
The version with the block body is also correct if the block contains single statements or expressions:
val x = 5 if(x > 10) println("greater") else println("smaller")
Java, however, treats if
as a statement while Kotlin treats if
as an expression. This is the main difference, and this fact allows us to use more concise syntax. We can, for example, pass the result of an if
expression directly as a function argument:
println(if(x > 10) "greater" else "smaller")
We can compress our code into single line...