because ‘XXX‘ is a local variable that is captured by a changing closure
Kotlin代码开发中,智能类型转换是非常有助于提高开发效率。但是在lambda函数闭包中捕获可变变量时,智能转换不适用于该变量,无论是在lambda内部还是在lambda创建后的声明范围内。
举个例子,下面的代码片段:
/*
* Your task is to implement the indexOfMax() function so that it computes returns
* the greatest index of the greatest element in the array, or null if the array is empty
*/
package maxindex
fun indexOfMax(a: IntArray): Int? {
var maxI: Int? = null
a.forEachIndexed { i, value ->
if (maxI == null || value >= a[maxI]) {
maxI = i
}
}
return maxI
}
在有些代码编辑器可能不会提醒,但是编译的时候会报这个错误:Smart cast to 'SearchResultData' is impossible, because 'currentSearchResultData' is a local variable that is captured by a changing closure
这是因为该函数可能会脱离其封闭范围,并可能稍后在不同的上下文中执行,可能多次执行,也可能并行执行。编译器必须在这种情况也生成正确的代码,因此它不会假设变量的值在空检查后保持不变,不能智能转换它。
这种编码场景目前还不能用智能类型转换,Koltin官方尚未实现该功能,可能会在将来的版本中解决。官方已有问题跟进:issue/KT-7186。
精彩的人生需要浪漫、无畏和勇气。