Search code examples
kotlingenericscastingnull

How to safe-cast a null into a generic type <T>?


I want to know if there's a way to make a safe cast from null, the next example throws an UNCHECKED CAST warning:

fun <T> notInitialized(): T = null as T

So, If anyone has an idea of how to make a safe cast from this function please let me know!


Solution

  • As an alternative to the generic answer (which is the usual way to approach these things), you could do this:

    fun notInitialised(): Nothing? = null
    

    Nothing is the ‘bottom’ type, which has no values and is the subset of all other types. So Nothing? is a type with just one value (null), and is a subtype of all nullable types. This means you can assign it to any nullable type without needing any type inference, e.g.:

    val a: Int? = notInitialised()
    

    But I still don't understand the purpose of this — it doesn't seem to have any benefit over just using null directly. If you're using null to represent an uninitialised value (as opposed to an unknown value, a missing value, an inapplicable value, an unavailable value, an undefined value, an unchanged value, a secret value, or any of the other subtly-different things that people use null to mean), then that should be spelled out in the property/method/variable's doc comment — in which case there's no point spelling it out again in the code.