How to reference the instance of the outside class

2019-02-16 05:42发布

问题:

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!

回答1:

You can use this@MainActivity to reference the outer class instance.

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