Can anyone please explain why doing this in Kotlin is impossible?
val x :Int? = 123
val y :Any = x
I come from .NET background where Nullable type is assignable to Object type, but how are they different?
Nullable types are not subtypes of Any
, but they are subtypes of Any?
.
Any
is only a superclass of non-nullable types. This makes it possible to write code that requires a non-null instance of anything, and still benefit from the safety of the type-checker (unlike when using Java's Object
).
Here is an image that can help:
The following code is a valid replacement of yours:
val x: Int? = 123
val y: Any? = x
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments