August 2017
Intermediate to advanced
440 pages
10h
English
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, because the result of the if expression (of type String) is evaluated and then passed ...
Read now
Unlock full access