Why can "return" return a "return" in Kotlin?

Willi Mentzel :

The question may sound silly, but there is no typo in it.

fun test(): Any {
    return return true
}

This is actually possible in Kotlin. Although the compiler warns about

Unreachable code

for the outer return. But this is just a warning.

I don't want to compare Java with Kotlin, but I was interested whether the same would work in Java.

public class Test {
  // ...
  static int test() {
    return return 1;
  }
}

It does not!

/Test.java:8: error: illegal start of expression
      return return 1;
                 ^
/Test.java:8: error: not a statement
      return return 1;
                           ^
2 errors

Why was Kotlin designed this way?

zsmb13 :

return is an expression in Kotlin, with a return type of Nothing, the type that acts as a subtype of all other types. This enables you to, for example, do this in a type safe way and without extra lines of null checks:

fun getInt(): Int? = ...

fun printInt() {
    val int: Int = getInt() ?: return
    println(int)
}

The type of getInt() ?: return can be Int here, because that's the closest common supertype of the two sides of the Elvis operator, thanks to Nothing being a subtype of Int.

The same thing applies for throw, which you can also use neatly with the Elvis operator to indicate that you want to cancel execution on a null value without having to worry about types later.

This results in an odd quirk where things like

fun x(): Int {
    return return throw return throw throw return 0
}

are valid syntax, because the Nothing type makes each of the expressions valid read from right to left. What will actually happen is that return 0 will execute and the rest of the code will never be reached, as the compiler warns.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=433928&siteId=1