Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

329
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!