IntelliJ向我显示了上下文提示,我的变量类型为(String..String?).我在网上找不到任何关于它的内容,这是什么类型的?

enter image description here

推荐答案

(String..String?) represents a flexible type with lower bound String and upperbound String? (nullable string). This is not valid Kotlin code (it's not denotable) but it is used in the compiler internals and thus in IntelliJ's hints sometimes.

(On the JVM we often see platform types using ! as in String!, which are a more specific case of flexible types)

It's Kotlin's way of saying it doesn't know whether the String type declared for payload.email is nullable or not (for instance if this is declared in Java, which doesn't distinguish those), and yet it doesn't want to enforce either of those, for convenience (hence "flexible").

顾名思义,灵活类型是灵活的——类型(L..U)的值可以在任何上下文中使用,其中需要L和U之间的一种可能类型

这意味着,即使该值的实际类型为"somewhere between 100 and 101",也可以在预期为String的位置使用该类型的值,即使该值的实际类型可能为String?,因此该值可能为空.

This is useful because assuming it is String would mean that null checks would be marked as redundant, and assuming it is String? would force the developer to write null checks everywhere, even though they might know that this particular Java method cannot return null.

In general, it's a good practice to explicitly declare the type of a variable that you get from Java, to avoid the propagation of the platform type and the uncertainty (and unsafety) that comes with it:

val email: String = payload.email // if you know it cannot be null
val email: String? = payload.email // if you don't know

Kotlin相关问答推荐

在调用父构造函数之前重写类属性

我需要后台工作才能使用卡夫卡的消息吗?

如何使用Kotlinx.LocalDateTime获取重置时间为00:00的当前日期?

为什么Kotlin不用static inner class来实现带有object关键字的单例呢?

在kotlin中匹配多个变量

Kotlin 可空泛型

修改器的属性是什么,我需要更改以使角变圆且宽度更小?喷气背包组合

使用启动或使用 coroutineScope 启动协程之间的区别

如何在 kotlin 中创建自定义迭代器并添加到现有类?

验证构造函数中的值组合

Kotlin 日期格式从一种更改为另一种

判断 AAR 元数据值时发现的一个或多个问题:

下拉通知面板时是否可以暂停Android中的任何视频(媒体播放器)应用程序?

`this@classname` 在 Kotlin 中是什么意思?

如何在调试中修复 ClassNotFoundException: kotlinx.coroutines.debug.AgentPremain?

如何在 kotlin 的片段类中更改 ActionBar 标题?

将多个 Kotlin 流合并到一个列表中,而无需等待第一个值

Kotlin 中更好的回调方法是什么?侦听器与高阶函数

Kotlin Android:属性委托必须有一个 'getValue(DashViewModel, KProperty*>)' 方法

Kotlin 错误:public function exposes its 'public/*package*/' return type argument