如何在Kotlin中引用外部类的实例? [英] How to reference the instance of the outside class in Kotlin?
问题描述
我在一个匿名内部类中,并且想要引用外部类的实例.在Java中,可以使用.this
引用它,并在其后加上类名以解决歧义.像:MainActivity.this
.如何在Kotlin中实现相同目标?因为当我这样做时,编译器会抱怨'expression 'this' cannot be a selector(occur after a dot)'
.谢谢!
I'm inside an anonymous inner class and wanting to reference the instance of the outside class. In Java it can be referenced using .this
preceded by the class name to resolve ambiguity. Like: MainActivity.this
. How can I achieve the same in Kotlin? Because the compiler is complaining 'expression 'this' cannot be a selector(occur after a dot)'
when I do that. Thanks!
推荐答案
您可以使用this@MainActivity
引用外部类实例.
You can use this@MainActivity
to reference the outer class instance.
提示:我也不记得语法,所以我只是用Java写了一个简单的示例,并要求IntelliJ将类转换为Kotlin来找到答案.
Tip: I couldn't remember the syntax either, so I just wrote a simple example in Java and asked IntelliJ to convert the class to Kotlin to find the answer.
这篇关于如何在Kotlin中引用外部类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!