Return last expression to block

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?

+6
source share
2 answers

you misunderstand curly braces {}when around with the whole operator flow-controlit’s just a block, eg:

if (condition) { //block here
} 

WHEN {} declared separately, this is a lambda expression , for example:

val lambda: () -> Int = { 1 }; // lambda

lambda if-else, {} (), block lambda {} , :

val lambda1: () -> Int = if (condition) { { 1 } } else { { 2 } };
val lambda2: () -> Int = if (condition) ({ 1 }) else ({ 2 });
val lambda3: () -> Int = if (condition) { -> 1 } else { -> 2 };

- , Unit. Unit - - Unit. .

, function return, , a Unit:

fun z(): Int { return 1; }

return Nothing, return , Nothing, :

fun nothing(): Nothing {
    return ?;// a compile error raising
}

, , :

fun z() = 1;
+4

"" , "y" - , :

val block: () -> Int = { 5 }
val five: Int = { 5 }()
val anotherFive = block()

, , , "()". , z :

fun z() : Int = { println("something") 1 }()

(, , )

+2

All Articles