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

Time:05-27

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!

CodePudding user response:

You can do fun <T> notInitialized(): T? = null - you need to return a nullable type (otherwise your cast is explicitly unsafe), and since you're already specifying the return type you don't need to cast null as T?. Or you could do that and skip the return type, fun <T> notInitialized() = null as T?

Either way you're just returning null, which isn't any specific type - you're just telling the caller to treat it as one. And that type needs to be nullable

CodePudding user response:

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.

  • Related