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

Ruxo

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?

Joffrey

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:

enter image description here

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.

edited at
0

Comments

0 comments
Login to comment

Related

Why can I assign null to value of Type "struct Nullable<T>" but not to my struct?

Why I can't use nullable type in flutter

Why I can't return a generic nullable value type and nullable reference type?

Why can't assign I <? extends Type> to <Type>?

Why can't I assign a typescript generic type to a union of that type?

Why is KClass declared as KClass<T : Any> and not KClass<T> so that the type argument can be nullable

Why can't I assign Nothing to a variable of type Unit?

Why can't I assign default to my notnull generic type?

Can't assign type any to string in Typescript, but i am trying to assign a string value

is there any way I send a nullable Function<T,R> as parameter in Kotlin?

Why I can't use a Class type as a generic parameter in Kotlin?

Why T? is not a nullable type?

Why intent.getParcelableExtra don't return nullable type in kotlin?

Why can't I assign type's value to an interface implementing methods with receiver type pointer to that type?

Why can't type parameter in Kotlin have any other bounds if it's bounded by another type parameter?

If null is a data type, why can't I assign a variable with type of null?

Why can't I assign a value to LiveData?

Why can't I assign a *Struct to an *Interface?

Why can't I assign lambda to Object?

Why can't I assign an object as shown?

Why can't I assign value on didSet?

Why can't I assign this pointer?

Why can't I assign a value to an "in" value

Why Can't Kotlin Infer The Type For Comparator

Why can't I assign to unique_ptr of type uint_8[]?

TypeScript: Why can't I assign a valid field of an object with type { a: "a", b: "b" }

Why can't I assign a struct variable an element of an array of the same type of structs?

Why can I assign a type that doesn't implement Copy from an inner scope to a mutable variable in an outer scope?

Why can I assign an interface to a variable without any values?

TOP Ranking

HotTag

Archive