Control flow as expressions
An expression is a statement that evaluates to a value. The following expression evaluates to true
:
"hello".startsWith("h")
A statement, on the other hand, has no resulting value returned. The following is a statement because it assigns a value to a variable, but does not evaluate to anything itself:
val a = 1
In Java, the common control flow blocks, such as if...else
and try..catch
, are statements. They do not evaluate to a value, so it is common in Java, when using these, to assign the results to a variable initialized outside the block:
public boolean isZero(int x) { boolean isZero; if (x == 0) isZero = true; else isZero = false; return isZero; }
In Kotlin, the if...else
and try..catch
control flow blocks are expressions. This means the result can be directly assigned to a value, returned from a function, or passed as an argument to another function...