我跟随kotlinc REPL中的
http://kotlinlang.org/docs/reference/null-safety.html中的命令,但遇到错误.首先,我定义了一个可以为空的字符串b:
>>> var b: String? = "abc"
但是,如果我尝试在其上进行“智能投射”,我会收到此错误:
>>> var l = if (b != null) b.length else -1
error: smart cast to 'String' is impossible, because 'b' is a mutable property that could have been changed by this time
var l = if (b != null) b.length else -1
^
我注意到,如果我将b定义为val而不是var,则该示例有效,但这不是文档中的内容:
文档中可能有拼写错误吗?
最佳答案 行为取决于变量的范围.见下面的例子:
class Foo {
var b: String? = "abc"
fun hello() {
if (b != null) b.length else -1 // Not gonna work
}
}
在上面的例子中,我们不能进行智能转换,因为b是一个实例变量,它可以在任何时候被另一个线程更改.
但是,在此示例中:
class Foo {
var b: String? = "abc"
fun hello() {
var bLocal: String? = str
if (bLocal!= null) bLocal.length else -1 // Works!
}
}
bLocal是var和String?就像上一个例子中的b一样,但这是有效的,因为bLocal是一个局部变量,编译器肯定知道这不能改变.
编辑:
从documentation开始:
- val local variables – always except for local delegated properties;
- val properties – if the property is private or internal or the check is performed in the same module where the property is declared. Smart casts aren’t applicable to open properties or properties that have custom getters;
- var local variables – if the variable is not modified between the check and the usage, is not captured in a lambda that modifies it, and is not a local delegated property;
- var properties – never (because the variable can be modified at any time by other code).