无法从匿名类访问外部类

我不能从匿名内部访问外部方法

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 <closure-BrandsBarView$1> Cause: Don't know how to generate outer expression for class <closure-BrandsBarView$1> 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() } } 

工作正常

在匿名类中, 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 } }) } 

为了帮助你的情况,很高兴看到课堂层次结构。