cdroid
cdroid

Reputation: 1622

Kotlin outer scope

I would like to access the scope of the calling class when creating an "anonymous inner class" in Kotlin. What would be the equivalent of Java's OuterScope.this syntax? example :

open class SomeClass {
    open fun doSomething() {
        // ...
    }
}

class MyClass {
    fun someFunc() {
        object : SomeClass() {
            override fun doSomething() {
                super<SomeClass>.doSomething()
                // Access the outer class context, in Java
                // this would be MyClass.this
            }
        }
    }
}

Upvotes: 50

Views: 14954

Answers (2)

Tushar Pandey
Tushar Pandey

Reputation: 4857

in my case i accessed it like : this@MainActivity

class MainActivity : AppCompatActivity() {
   inner class Anon : Observer<PagedList<ApplicationUsers>> {
        override fun onChanged(pagedList: PagedList<ApplicationUsers>?) {
            Toast.makeText(this@MainActivity, "hello", Toast.LENGTH_SHORT).show()
        }
    }
}

Upvotes: 14

bashor
bashor

Reputation: 8453

this@MyClass

JFYI: the same syntax for access to receiver of extension function:

fun MyClass.foo() {
    // in some nested thing:
    this@foo
    //...
}

Kotlin Reference: This expressions

Upvotes: 103

Related Questions