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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With