只在Kotlin中返回null的函数

Cas*_*ash 7 kotlin

是否可以声明一个只返回的函数null?不幸的是,你不能null在返回类型部分写.返回值应该是null而不是Unit,以便它可以与可空操作符一起使用.

s1m*_*nw1 6

正如评论中所建议的那样,Nothing?应该是这样一个函数的返回类型:

fun alwaysNull(): Nothing? = null
Run Code Online (Sandbox Code Playgroud)

文件规定:

[...]您可能遇到此类型的另一种情况是类型推断.这种类型的可空变体Nothing?只有一个可能的值,即null.如果您使用null初始化推断类型的值并且没有其他信息可用于确定更具体的类型,则编译器将推断Nothing?类型:

val x = null           // 'x' has type `Nothing?`
val l = listOf(null)   // 'l' has type `List<Nothing?>
Run Code Online (Sandbox Code Playgroud)