我想在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
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
bas*_*hor 58
this@MyClass
Run Code Online (Sandbox Code Playgroud)
JFYI:访问扩展功能接收器的语法相同:
fun MyClass.foo() {
// in some nested thing:
this@foo
//...
}
Run Code Online (Sandbox Code Playgroud)
Kotlin参考:这个表达式
就我而言,我像这样访问它: 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()
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6135 次 |
| 最近记录: |