【问题标题】:Kotlin: calling outer class method in object expressionKotlin:在对象表达式中调用外部类方法
【发布时间】:2018-07-30 09:44:49
【问题描述】:

我的问题和Java: calling outer class method in anonymous inner class 差不多。 但这次我们使用的是 Kotlin。

如下例,我想在对象表达式中调用funB(),但我只失败了两次。

class A {
    lateinit var funA: () -> Unit
    lateinit var funB: () -> Unit

    fun funC()  {
        var b = object : B() {
            override fun funB() {
                funA() // A.funA()

                // Two attempts to fail
                funB() // b.funB(), not my expect
                A::funB() // compile error
            }
        }
    }
}

感谢您的回答!

【问题讨论】:

  • this@A.funB()
  • @yole 这就是答案 ;)

标签: kotlin


【解决方案1】:

您可以使用 @ 限定 this 以获得等效的 java:MyClass.this ->this@MyClass

那么在你的情况下,你可以调用:

this@A.funB()

来自doc

要从外部作用域(类、扩展函数或带有接收器的标记函数字面量)访问 this,我们编写 this@label ,其中@label 是 this 应该来自的作用域上的标签:

class A { // implicit label @A
    inner class B { // implicit label @B
        fun Int.foo() { // implicit label @foo
            val a = this@A // A's this
            val b = this@B // B's this

            val c = this // foo()'s receiver, an Int
            val c1 = this@foo // foo()'s receiver, an Int

            val funLit = lambda@ fun String.() {
                val d = this // funLit's receiver
            }


            val funLit2 = { s: String ->
                // foo()'s receiver, since enclosing lambda expression
                // doesn't have any receiver
                val d1 = this
            }
        }
    }
}

【讨论】:

  • 非常感谢您的回答!好详细!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-22
  • 1970-01-01
  • 1970-01-01
  • 2021-12-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多