一个感叹号在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?
推荐文章
- Kotlin中惯用的登录方式
- 如何在Kotlin中实现生成器模式?
- Kotlin中的单个感叹号
- 如何允许所有网络连接类型HTTP和HTTPS在Android(9)馅饼?
- 如何克隆或复制一个列表在kotlin
- 如何将字符串转换为长在Kotlin?
- 如何在Kotlin解析JSON ?
- 什么Java 8流。收集等价物可在标准Kotlin库?
- Android房间-简单的选择查询-不能访问数据库在主线程
- 如何检查“instanceof”类在kotlin?
- “by”关键字在Kotlin中做什么?
- 导航目标xxx对于这个NavController是未知的
- 我如何解决错误“minCompileSdk(31)指定在一个依赖的AAR元数据”在本机Java或Kotlin?
- 模块是用不兼容的Kotlin版本编译的。其元数据的二进制版本为1.5.1,预期版本为1.1.15
- Kotlin: Public get private set var