我正在使用 kotlin 开发一个 android 应用程序,Android Studio 自动完成菜单显示了这个(我正在详细说明服务器响应)
如您所见,message
和 status
是两个字符串,但第一个标记为 String!
,另一个标记为String
,但我不明白其中的区别
我尝试检查 (java) 源代码并且 status
被标记为 @NonNull
,而 message
没有任何注释,但是如果在这种情况下,在 kotlin 中字符串可以为空,我应该使用 !!
运算符访问它,并且它应该用 ?
标记,而不是用 !
,因为它将是 String?
类型。
这是怎么回事?
标有!的类型来自 Java,它们被称为平台类型
。这意味着 Kotlin 编译器不知道该值是否可以为 null,因为没有找到它们的可空性注释。
来自official documentation:
Null-checks are relaxed for such types, so that safety guarantees for
them are the same as in Java
您应该小心这些类型,因为它们会导致运行时异常:
When we call methods on variables of platform types, Kotlin does not
issue nullability errors at compile time, but the call may fail at
runtime, because of a null-pointer exception or an assertion that
Kotlin generates to prevent nulls from propagating