我无法从匿名内部访问外部方法
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 classCause: 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() } }
工作正常
在匿名类中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 } }) }
为了帮助你的情况,看到类层次结构会很高兴.