A function that only returns null in Kotlin

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

+5
source share
1 answer

As also suggested in the comments, Nothing? must 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. Variant with a null value of this type Nothing? has exactly one possible value, which is null . If you use null to initialize the value of the output type and there is no other information that can be used to determine a more specific type, the compiler will infer the type Nothing? :

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

Source: https://habr.com/ru/post/1275827/


All Articles