Reputation: 118742
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
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 isnull
. If you usenull
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 theNothing?
type:val x = null // 'x' has type `Nothing?` val l = listOf(null) // 'l' has type `List<Nothing?>
Upvotes: 15