Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference the instance of the outside class in Kotlin?

Tags:

kotlin

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!

like image 611
Jezer Crespo Avatar asked Mar 14 '16 07:03

Jezer Crespo


People also ask

How do you access one class variable from another class in Kotlin?

How do I make a variable in one class that can be accessed by another class in Kotlin? You need to reference an instance of the other class and use . dot notation to access its properties. someInstanceOfA.

What does ?: Mean in Kotlin?

In certain computer programming languages, the Elvis operator ?: is a binary operator that returns its first operand if that operand is true , and otherwise evaluates and returns its second operand.

How do I get the instance of abstract class in Kotlin?

In Kotlin, we cannot create an instance of an abstract class. Abstract classes can only be implemented by another class which should be abstract in nature. In order to use an abstract class, we need to create another class and inherit the abstract class.


1 Answers

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.

like image 157
JB Nizet Avatar answered Oct 12 '22 23:10

JB Nizet