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!
:: 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.
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.
In Kotlin, the “this” keyword allows us to refer to the instance of a class whose function we happen to be running.
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
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With