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

335
Visualizações
Why can a java nullable returned value be assigned to a Kotlin Non-Nullable variable?

I'm very surprise that the following code is compiled:

lateinit var progressBar: ProgressBar

and in onCreate:

progressBar = view.findViewById(R.id.pb_loader)

findViewById declared that it can return a null, so how doesn't the compiler enforce me to declare:

lateinit var progressBar: ProgressBar?

Can someone help me to understand when the compiler does enforce and when it doesn't?

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

0

View.findViewById is a Java function. The Kotlin compiler has no way of determining if it can return a nullable value or not since for Java only nullable types exist (even though they might never be null at runtime).

Annotations were introduced for the sake of documentation (and interoperability). Some of them can be used by the Kotlin compiler to determine the proper type.

But if the compiler cannot decide the type is regarded as platform type, which means you as a developer have to decide at call-site if the value returned might be null.

over 4 years ago · Santiago Trujillo Relatório

0

From the docs:

Any reference in Java may be null, which makes Kotlin's requirements of strict null-safety impractical for objects coming from Java. Types of Java declarations are treated specially in Kotlin and called platform types. Null-checks are relaxed for such types, so that safety guarantees for them are the same as in Java

So yeah, this is expected behaviour. Kotlin doesn't check nullability if it comes from a Java API, unless you put nullability annotations on the method. findViewById unfortunately does not have such annotations.

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