变量被声明为 var 但编译器说它是 val

Variable is declared as var but compiler is saying it val

编译器给我错误

Error:(97, 17) Val cannot be reassigned

但是变量声明为var

编辑: 你可以在我的代码中看到注释。当我分配 rcv = recyclerView
chkStrictSearch = checkBox 我在上面的错误消息工具提示中有红色下划线

下面是我的代码:

private var rcv: RecyclerView? = null
private var chkStrictSearch: android.widget.CheckBox? = null  

private fun getMainView(): View{
    return with(context){
        frameLayout{
            lparams(width = matchParent, height = matchParent)
            //Error is below - val cannot be reassign
            rcv = recyclerView{
                lparams(width = matchParent, height = matchParent)
                setPadding(0, resources.getDimension(R.dimen.toolbar_height).toInt(), 0, dip(48))
                clipToPadding = false
            }
           //and here - val cannot be reassign
            chkStrictSearch = checkBox{
                text = "Strict Search"
            }.lparams(width = wrapContent, height = wrapContent){
                marginEnd = dip(24)
                bottomMargin = dip(50)
                gravity = Gravity.BOTTOM
            }
        }
    }
}  

好像是静态代码分析的bug,也可能是增量编译导致的。尝试 rebuild/clean 项目。

或者试试这个:

private fun getMainView(): View {
    return with(context) {
        frameLayout {
           rcv = null
        }
    }
}

如果现在编译正常,请添加回您的原始代码并重新编译。