Casebash
Casebash

Reputation: 118742

Function that only ever returns null in Kotlin

Is it possible to declare a function that only ever returns null? Unfortunately, you cannot write null in the return type section. The return value should be null and not Unit so that it can work with nullable operators.

Upvotes: 13

Views: 1464

Answers (1)

s1m0nw1
s1m0nw1

Reputation: 81859

As also suggested in the comments, Nothing? should be the return type of such a function:

fun alwaysNull(): Nothing? = null

The documentation states:

[...] Another case where you may encounter this type is type inference. The nullable variant of this type, Nothing?, has exactly one possible value, which is null. If you use null to initialize a value of an inferred type and there's no other information that can be used to determine a more specific type, the compiler will infer the Nothing? type:

val x = null           // 'x' has type `Nothing?`
val l = listOf(null)   // 'l' has type `List<Nothing?>

Upvotes: 15

Related Questions