[英]Why intent.getParcelableExtra don't return nullable type in kotlin?
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.我收到的结果是一个不可为空的变量,但它可以为空,因为我不知道该 Parcelable 是否已添加到附加项中。 Why kotlin doesn't return a nullable type?
为什么 kotlin 不返回可空类型?
Kotlin just calls getParcelableExtra()
as it is defined in in the android SDK in java. Kotlin 只是调用
getParcelableExtra()
因为它在 java 的 android SDK 中定义。 This method is not annotated with @Nullable
so kotlin doesn't know it might return null.此方法未使用
@Nullable
注释,因此 kotlin 不知道它可能返回 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.具有可空性注释的 Java 类型不表示为平台类型,而是表示为实际的可空或非空 Kotlin 类型。 The compiler supports several flavors of nullability annotations, including:
编译器支持多种可空性注释,包括:
- JetBrains (@Nullable and @NotNull from the org.jetbrains.annotations package)
JetBrains(来自 org.jetbrains.annotations 包的 @Nullable 和 @NotNull)
- Android (com.android.annotations and android.support.annotations)
Android(com.android.annotations 和 android.support.annotations)
In the code在代码中
val screen = intent.getParcelableExtra<Screen>("screen")
the inferred type of screen
will be Screen!
推断的
screen
类型将是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:但是,如果您积极希望 Kotlin 强制执行空安全,则可以明确指定类型:
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.通过显式指定类型,Kotlin 将为您提供您习惯的所有编译时空值安全性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.