当前位置:  开发笔记 > Android > 正文

无法从匿名类访问外部类

如何解决《无法从匿名类访问外部类》经验,为你挑选了1个好方法。

我无法从匿名内部访问外部方法

class MyClass()
{
    fun doSomeStuff()
    {
       for (brandView in holder.brandImages)
       {
           brandView.onClick {
               if (brandView.brandId != null)
               {
                   notifyStateChanged()
               }
           }
       }
    }
    fun notifyStateChanged()
    {
        print("something")
    }
}

我有编译时错误:

Error:(46, 31) org.jetbrains.kotlin.codegen.CompilationException: Back-end (JVM) Internal error: Don't know how to generate outer expression for class 
Cause: Don't know how to generate outer expression for class 
File being compiled and position: (46,31) in C:/Users/piotr/IdeaProjects/MerciIt/app/src/main/java/pl/com/digita/merciit/app/ui/controls/colorswitcher/brandsbar/BrandsBarView.kt
PsiElement: {
                if (brandView.brandId != null)
                {
                    notifyStateChanged()
                    //brandView.setTicked(!brandView.isTicked)
                }
            }
The root cause was thrown at: CodegenContext.java:160
    at org.jetbrains.kotlin.codegen.ExpressionCodegen.genQualified(ExpressionCodegen.java:299)
(...)

那么我做错了什么?

仅供理论讨论:

for (brandView in holder.brandImages)
{
    setupBrandView(brandView)
}

fun setupBrandView(brandView: BrandTickerView)
{
    brandView.onClick {brandView.isTicked = !brandView.isTicked; dataChanged?.invoke() }

}

工作正常



1> vigilancer..:

在匿名类中this引用外部类.从object外活动,必须明确提及

class MainActivity : Activity() {
    public override fun onCreate(savedInstanceState: Bundle?) {
...
        text_view.setOnClickListener{ v ->
            this.doActivityStuff()
        }
...
    fun doActivityStuff() {
        // do some stuff
    }
    text_view.setOnClickListener(object : View.OnClickListener {
        override fun onClick(v: View?) {
            this.onClick(v) // this refer to onClickListener
            this@MainActivity.doActivityStuff() // this refer to MainActivity
        }
    })
}

为了帮助你的情况,看到类层次结构会很高兴.

推荐阅读
mobiledu2402851203
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有