if
-Expression
In Kotlin, if
is not just a statement (as in Java), but rather an expression, so it returns a value.
val oddOrEven = if (i % 2 == 0) "even" else "odd"
So if
returns the value of the branch that matches the condition.
That’s why the well-known ?:
operator in Java is superfluous, because you can map its functionality with if
… else
.
Incidentally, this also applies to many other expressions, such as try
/catch
blocks:
val contents = try {
file.readText ()
} catch (ex: Exception) {
"File could not be loaded: $ex"
}