一个感叹号在Kotlin中是什么意思?我已经见过几次了,尤其是在使用Java api时。但我在文档和StackOverflow上都找不到它。


当前回答

它们被称为平台类型,它们意味着Kotlin不知道该值是否可以为空,它由您决定是否为空。

In a nutshell, the problem is that any reference coming from Java may be null, and Kotlin, being null-safe by design, forced the user to null-check every Java value, or use safe calls (?.) or not-null assertions (!!). Those being very handy features in the pure Kotlin world, tend to turn into a disaster when you have to use them too often in the Kotlin/Java setting. This is why we took a radical approach and made Kotlin’s type system more relaxed when it comes to Java interop: now references coming from Java have specially marked types -- Kotlin Blog

其他回答

它们被称为平台类型,它们意味着Kotlin不知道该值是否可以为空,它由您决定是否为空。

In a nutshell, the problem is that any reference coming from Java may be null, and Kotlin, being null-safe by design, forced the user to null-check every Java value, or use safe calls (?.) or not-null assertions (!!). Those being very handy features in the pure Kotlin world, tend to turn into a disaster when you have to use them too often in the Kotlin/Java setting. This is why we took a radical approach and made Kotlin’s type system more relaxed when it comes to Java interop: now references coming from Java have specially marked types -- Kotlin Blog

它是平台类型的符号:

T !意思是“T还是T?”

我用有趣的解释来记住这些事情:

?:我不知道它是否为空。 小心!这可能是空的。 !!小心点,是的,我知道。它总是不为空的。

用!表示的类型称为平台类型,这是一个来自Java的类型,因此很可能是null。这是Kotlin编译器在调用Java时默认推断的内容(对于最基本的情况,可以通过注释Java方法来解决这个问题)。您应该将平台类型处理为可空类型,除非您确实知道特定的API永远不会返回null。编译器允许将平台类型赋值给可空类型和非空类型的变量。

平台类型符号 […] T !意思是“T还是T?”[…]

您可以将平台类型称为“未知可空性类型”。同样重要的是,您不能为自己的类型使用感叹号类型,它不是Kotlin语法的一部分,它只是一种符号。

我已经见过几次了,尤其是在使用Java api时

正如s1m0nw1, T!是T还是T?下一个问题是:T是什么??https://kotlinlang.org/docs/reference/null-safety.html上有详细的文档。与Java不同,Kotlin不允许某些元素为空,例如String

为了允许空值,我们可以将变量声明为可空字符串,写入 字符串?: var b:字符串?=“abc” B = null // ok […] b ?长处 如果b不为空,则返回b.length,否则返回null。这个表达式的类型是Int?