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

不可达代码

为外部返回.但这只是一个警告.

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

为什么Kotlin 是这样设计的?

推荐答案

return是Kotlin中的一个表达式,返回类型为Nothing,该类型充当所有其他类型的子类型.例如,这使您能够以类型安全的方式执行此操作,而无需额外的null行判断:

fun getInt(): Int? = ...

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

这里getInt() ?: return的类型可以是Int,因为这是Elvis运算符两侧最常见的超类型,因为NothingInt的子类型.

同样的道理也适用于throw,您也可以巧妙地将其与Elvis运算符结合使用,以指示您希望取消对null值的执行,而不必担心以后的类型.

这导致了一种奇怪的怪事,比如

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

是有效语法,因为Nothing类型使每个表达式从右向左读取都有效.正如编译器警告的那样,实际情况是return 0将被执行,而其余的代码将永远无法到达.

Kotlin相关问答推荐

当通过firstOrders访问时,存储在伴随对象中的对象列表具有空值

Scala性状线性化等价于Kotlin

捕捉异常是Kotlin协程中的反模式吗?

相当于roomdb中的DateTime Bigint列的是什么

如何检测一个值是否是Kotlin中的枚举实例?

如何处理基于枚举提前返回的 forEach 循环,Kotlin 中的一条路径除外

如何在 Kotlin 中将with代码转换为完整代码?

多个不同的指针输入

如何在 Kotlin 中为变量分配另一个变量的值?

如何将jooq multiset的结果映射到Hashmap(Java Map)?

如何为你的 Flutter 元素添加 Kotlin 支持?

将 jetpack compose 添加到现有元素

验证和 DDD - kotlin 数据类

从片段(fragment)中的点击事件启动协同程序

Kotlin 中更好的回调方法是什么?侦听器与高阶函数

如何为 Java 调用者声明返回类型为void的 Kotlin Lambda?

在Kotlin中将列表转换为对的惯用方法

lateinit 的 isInitialized 属性在伴随对象中不起作用

有没有办法在Kotlin中设置一个私有常量

Kotlin反射不可用