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

Viewed 3330

I have an example of extracting data from intent

val screen = intent.getParcelableExtra<Screen>("screen")

The result I received is a not nullable variable, but it can be null because I don't know if that parcelable has been added to extras. Why kotlin doesn't return a nullable type?

2 Answers

Kotlin just calls getParcelableExtra() as it is defined in in the android SDK in java. This method is not annotated with @Nullable so kotlin doesn't know it might return null.

Also see nullability annotations:

Nullability annotations
Java types which have nullability annotations are represented not as platform types, but as actual nullable or non-null Kotlin types. The compiler supports several flavors of nullability annotations, including:

  • JetBrains (@Nullable and @NotNull from the org.jetbrains.annotations package)
  • Android (com.android.annotations and android.support.annotations)

In the code

val screen = intent.getParcelableExtra<Screen>("screen")

the inferred type of screen will be Screen!. The exclamation mark indicates that this is a platform type, which means that it may or may not be nullable, but the compiler won't enforce null-checking behavior.

Read more: Null Safety and Platform Types

If you actively want Kotlin to enforce null safety, though, you can specify the type explicitly:

val screen: Screen? = intent.getParcelableExtra<Screen>("screen")

By specifying the type explicitly, Kotlin will give you all the compile-time null safety you're used to.

Related