解决Kotlin错误:Smart cast is impossible, because the property could have been changed by this time
使用Kotlin开发Android应用,在向列表添加Nullable值时Android Studio提示:
Smart cast to 'String' is impossible, because 'a.name' is a mutable property that could have been changed by this time
示例如下
class A {
var name: String? = null
}
class B {
val names: ArrayList<String> = ArrayList()
public fun addNames(a: A) {
if(a.name != null) {
names.add(a.name);
}
}
}
查了一下,报这个错误的原因是:在别的线程可以对Nullable值a.name做修改,这样在执行names.add(a.name)时它的值有可能为null。
解决
为了避免添加null值,有几种做法:
1、使用val声明nullable值,这样nullable值就不可能被修改
class A {
val name: String? = null
}
2、把nullable值赋值给一个新的变量,然后再做其他操作
public fun addNames(a: A) {
val name = a.name
if(name != null) {
names.add(name);
}
}
3、使用?let语法糖
a.name?.let { name -> names.add(name) }
a.name?.let { names.add(it) }
a.name?.let(names::add)