Avatar ·

Smart cast to 'Type' is impossible: 如何修复Kotlin中可变属性的错误?

大家好!我是Kotlin新手,遇到了一个令人困惑的错误。我有一个带有可变属性`var`的类,并尝试通过`is`进行类型检查,但编译器提示:"Smart cast to 'String' is impossible, because 'name' is a mutable property that could have been changed by this time"。 这是我的代码: ```kotlin class User { var name: Any = "John" fun printName() { if (name is String) { // 这里报错:Smart cast to 'String' is impossible println(name.length) } } } ``` 我明白`name`是`var`,但我在使用前已经检查了它的类型!为什么编译器不信任我?如何修复这个问题?在Java中使用`instanceof`检查时没有这样的问题。也许我遗漏了Kotlin的一些基础知识?请告诉我如何正确处理这种情况,使代码既能编译又安全。提前感谢! <<>>

为什么Kotlin中会出现Smart cast错误?

错