Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: calling outer class method in object expression

Tags:

kotlin

My question is almost like this question Java: calling outer class method in anonymous inner class . But this time we are in Kotlin.

As the example below, I want to call funB() in the object expression, but I only made two failures.

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

Thank you for your answer!

like image 566
Bear Big Avatar asked Jul 30 '18 09:07

Bear Big


People also ask

What does :: mean in Kotlin?

:: is just a way to write a lambda expression basically we can use this to refer to a method i.e a member function or property for example class Person (val name: String, val age: Int) Now we can write this to access the person which has the maximium age.

Can inner class calling Outer method?

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance. To instantiate an inner class, you must first instantiate the outer class.

What is this () in Kotlin?

In Kotlin, the “this” keyword allows us to refer to the instance of a class whose function we happen to be running.


1 Answers

You can qualify this with a @ to obtain an equivalent of java: MyClass.this ->this@MyClass

Then in your case, you can call:

[email protected]()

From the doc:

To access this from an outer scope (a class, or extension function, or labeled function literal with receiver) we write this@label where @label is a label on the scope this is meant to be from:

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
            }
        }
    }
}
like image 70
crgarridos Avatar answered Oct 06 '22 01:10

crgarridos