为什么IntelliJ中的“Smart cast to kotlin.String”

时间:2018-01-28 17:25:42

标签: intellij-idea null kotlin

我用可空参数

编写了我的类
class MyClass(a: String? = null) {
    var b: String

    init {
        if( a == null ) {
            b = "N/A"
        }
        else {
            b = a
        }
    }
}

并注意到,IntelliJ警告b = a任务

Smart cast to kotlin.String

为什么这个警告以及如何避免它?

2 个答案:

答案 0 :(得分:6)

这不是警告,只是编译器知道您的变量a而不是 null的信息。因此,它可以用作String而不是可空String?,因此没有安全操作符,例如。

否则,您需要明确地将a: String?投射到String,以便将其分配给String变量b,如以下屏幕截图所示:

enter image description here

答案 1 :(得分:4)

这不是要避免的,这是一种称为smart cast的语言功能。

编译器检测到a在给定的代码路径上是非空值,因此您可以使用不可为空的String类型,它可以让您使用直接使用它而不必担心它的可空性。如果您没有进行智能投射,则必须手动将其从String?投射到String以调用其上的方法 - 或者将其分配给非可空的变量,就像你的情况一样。

另一个也许更容易理解智能投射开始的例子是子类。我们假设您有PersonCustomer个类,只有后者使用getPurchases()方法。

在Java中,您必须执行以下操作来调用所述方法:

if (p instanceof Customer) {
    ((Customer)p).getPurchases();
}

在Kotlin中,您可以在if区块内对您已经检查过的子类型进行智能投射:

if (p is Customer) {
    p.getPurchases()
}

如果您考虑一下,从String?String的演员阵容在工作中是相同的机制 - 您也可以将智能演员变为更具体的类型。

if (a != null)

给定a类型String?

基本相同
if (a is String)