Kotlin 科特林外窥镜
我想在创建“匿名内部类”时访问调用类的作用域 在科特林。Java的Kotlin 科特林外窥镜,kotlin,Kotlin,我想在创建“匿名内部类”时访问调用类的作用域 在科特林。Java的OuterScope.this语法的等价物是什么?例如: open class SomeClass { open fun doSomething() { // ... } } class MyClass { fun someFunc() { object : SomeClass() { override fun doSomething() {
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
}
}
}
}
打开类SomeClass{
开玩笑{
// ...
}
}
类MyClass{
fun someFunc(){
对象:SomeClass(){
覆盖有趣的doSomething(){
super.doSomething()
//在Java中访问外部类上下文
//这将是我的班级
}
}
}
}
JFYI:
访问扩展功能接收器的相同语法:
fun MyClass.foo() {
// in some nested thing:
this@foo
//...
}
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()
}
}
}
class MainActivity:AppCompatActivity(){
内类Anon:观测器{
更改后覆盖乐趣(页面列表:页面列表?){
Toast.makeText(this@MainActivity,“你好”,吐司。长度(短)。show()
}
}
}
Hi,如果在onChanged()中我想访问Anon类,那么可能吗?
class MainActivity : AppCompatActivity() {
inner class Anon : Observer<PagedList<ApplicationUsers>> {
override fun onChanged(pagedList: PagedList<ApplicationUsers>?) {
Toast.makeText(this@MainActivity, "hello", Toast.LENGTH_SHORT).show()
}
}
}