在对象表达式中调用

在对象表达式中调用

我的问题几乎就像这个问题 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 以获得等效的 java:MyClass.this -> this@MyClass
然后在您的情况下,您可以致电:

[email protected]()

doc :


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
            }
        }
    }
}

关于Kotlin:在对象表达式中调用外部类方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51591186/

10-10 19:57