variable that is captured by a changing closure

QuibblerQuibbler 2025-01-19 约 3 分钟 1255 次阅读

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。

相关推荐

精选
获取系统SDK版本、判断手机ROM
Code

获取系统SDK版本、判断手机ROM

Build获取系统SDK版本Android中部分API的使用,需要在特定的SDK版本之后才能使用,因此在兼容老版本SDK的时候,经常需要判断API的版本。各种Android版本的对应关系参考《Android各版本对应的SDK版本》判断手机ROM有时候需要判断手机系统的ROM,检测ROM是MIUI、EMUI还是Flyme,可以使用getprop命令,去系统build.prop文件(关于build.p

3.7k
精选
AndroidStudio中各种中文乱码问题
Code

AndroidStudio中各种中文乱码问题

AndroidStudio中各种中文乱码问题1、编译Java错误信息乱码在出现这个Annotation processors must be explicitly declared now...问题的时候,正好也发现AndroidStudio Build Output错误信息都乱码。经常遇到各种问题,习惯了,现在遇到的问题,都是以后的答案。 1.1、修改项目build.gradle(无效)在整个p

2.4k
AndroidStudio 报错:has no declaration in the base values folder
Code

AndroidStudio 报错:has no declaration in the base values folder

在资源文件中正常定义的值,也能编译运行。昨天还正常,今天一打开就报错。应该又是AndroidStudio自身的Bug了。原因众说纷纭,参考Stack Overflow 一篇类似的讨论。解决:File => Invalidate Caches / Restart => Invalidate and Restart.

4.4k