解决kotlin 安卓 'no name provided' is impossible, because 'recycler_view.adapter' is a complex expre
解决Kotlin错误:Smart cast is impossible, because the property could have been changed by this time
xll1990 2017.12.13 阅读 6156
今日荐书:《学会提问》,豆瓣评分8.3,批判性思维领域的“圣经”,看见诸多提问背后的真谛,具备互联网思维必读书之一
使用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)