android - Kotlin 中键入后的单个感叹号 "!"是什么意思?

标签 android kotlin kotlin-android

我正在学习使用 Kotlin 开发 Android 应用。我以前使用 Java 进行开发。在 Android Studio 中编码时,我可以看到 Lambdas、方法等中使用的返回类型、参数等都写成了 View!。

我知道 Kotlin 中类型后面的 ? 表示 Nullable 类型。 ! 是什么意思。

例如:

val item = mySpinner.selectedItem

返回类型是 Any! ! 是什么意思?意思是?它是否与 Nullable 类型相同,即 Any? ? 谢谢。

最佳答案

这是一个platform type表明 Kotlin 不确定它是 null 还是 not null,就像在说“也许”。

platform types can't be mentioned explicitly in the program, so there's no syntax for them in the language. Nevertheless, the compiler and IDE need to display them sometimes (for example, in error messages or parameter info), so there is a mnemonic notation for them:

  • T! means "T or T?",
  • (Mutable)Collection! means "Java collection of T may be mutable or not, may be nullable or not",
  • Array<(out) T>! means "Java array of T (or a subtype of T), nullable or not"

因为它可以是 nullnot null,所以如何处理它取决于您。

同时检查另一个 post

关于android - Kotlin 中键入后的单个感叹号 "!"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74341212/

相关文章:

java - Kotlin `this` 未在继承类中返回正确的实例

java - RxJava HashMap 转换

Android - 如何停止和暂停计时器

安卓视频流 : AsyncTask or UI thread?

android - IntentsRule 已弃用 Espresso

java - 如何从 Java 中获取 Kotlin 属性的注释?

gradle - 如何在IntelliJ/Kotlin中设置序列化?

textfield - 在 TextField Jetpack Compose 中用户输入文本后显示尾随图标