简体   繁体   中英

Why I can't assign nullable type to Any in Kotlin?

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

From the docs:

Kotlin's type system is aimed at eliminating the danger of null references from code, also known as the The Billion Dollar Mistake.

In Kotlin, the type system distinguishes between references that can hold null (nullable references) and those that can not (non-null references).

Example:

var a: String = "abc"
a = null // compilation error

var b: String? = "abc" //using `String?` allows you to assign null
b = null // ok
print(b)

Any is a class same as String , the only difference is that every class has Any as it's superclass. But the above that I wrote regarding NPE is applied to all types in kotlin.

Yes. The basic requirement for Kotlin variable is to be marked whether it is Nullable or not to avoid NPE.

Here in your case,

var x: Int? = 123

is assigned as nullable value with ? but when you mapped it to Any object, you have missed to add nullable ? to Any object

so var y: Any? = x var y: Any? = x

will do as we are marking nullable to y also.

The 1st line of code val x :Int? = 123 val x :Int? = 123 is clearly saying that the x is supposed to hold a value of type Int Kotlin provides the built-in type Int that is used to for representing numbers.

On the next line, val y :Any = x , y is supposed to hold a type of Any , which is the root of the Kotlin class hierarchy. Every Kotlin class has Any as a superclass.

So there is type mismatch - and hence Kotlin compiler complains that it cannot assign an Int to an object which you declared to hold type Any

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM