Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

383
Visualizações
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?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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
over 4 years ago · Santiago Trujillo Relatório

0

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.

over 4 years ago · Santiago Trujillo Relatório

0

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

will do as we are marking nullable to y also.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda