【问题标题】:Kotlin outer scopeKotlin 外部作用域
【发布时间】:2014-10-22 08:52:15
【问题描述】:

我想在创建“匿名内部类”时访问调用类的范围 在科特林。什么相当于 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
            }
        }
    }
}

【问题讨论】:

    标签: kotlin


    【解决方案1】:
    this@MyClass
    

    JFY: 访问扩展函数接收者的语法相同:

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

    Kotlin 参考:This expressions

    【讨论】:

      【解决方案2】:

      在我的情况下,我像这样访问它: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()里面我想访问匿名类,可以吗?
      猜你喜欢
      • 1970-01-01
      • 2013-04-09
      • 1970-01-01
      • 2019-07-16
      • 2023-03-08
      • 2020-10-21
      • 1970-01-01
      • 1970-01-01
      • 2020-04-30
      相关资源
      最近更新 更多