I am learning a new and very beautiful Kotlin language, and everything seems very logical and consistent. I found only one thing that seems to be an arbitrary exception to the rule than a solid rule. But perhaps I lack an understanding of some of the deeper reasons underlying this rule.
I know that in the statements if-elseand whenthere are blocks of code, then returns the last expression. In the following example, 1or are 2returned depending on the condition - in our case, it returns 1.
val x = if (1 < 2) {println("something"); 1} else {println("something else"); 2}
On the other hand, this is not performed for any code block. The next line assigns ynot 1, but to the entire block of code as lambda.
val y = {println("something"); 1}
Similarly, in the function body, the last expression is not returned. It does not even compile.
fun z() : Int {
println("something")
1
}
So what is the rule? Is it really as arbitrary as: if in the expression if-elseor when, which is used as an expression, there is a block of code, then the last expression in the block is returned. Otherwise, the last expression does not return to the outer region. Or am I missing something?
source
share