我对以下Kotlin声明感到困惑
val s = person.name ?: return
我知道那个?
用于无效安全…但是:return
做什么。
?:
被称为猫王操作员 。
val s = person.name ?: return
等于:
val s = if (person.name != null) person.name else return
这意味着如果person.name
为null
则返回。
?:
如果表达式左侧为null
返回右侧的表达式。
在这种情况下,不是给出一个值,而是立即从当前函数返回。 你也可以用类似的方式抛出一个异常,以防万一有些东西是null
而且你没有办法处理你将要做的事情。
这个例子基本上是下面的简写(假设name是一个String?
):
val s: String? = person.name if(s == null) { return } // you can use `s` here as it will be smart cast to `String`