Kotlin外部作用域

47

我想在Kotlin中创建一个"匿名内部类"时访问调用类的作用域,这应该怎么做?与Java的OuterScope.this语法相当的是什么?例子:

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
            }
        }
    }
}
2个回答

99
this@MyClass

顺便说一句:扩展函数访问接收者的语法与原函数相同:

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

Kotlin 参考文档:This expressions


14

在我的情况下,我像这样访问它: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()
        }
    }
}

嗨,在onChanged()内部我想访问匿名类Anon,这可能吗? - anticafe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接