I would like to access the scope of the calling class when creating an "anonymous inner class" in Kotlin. What would be the equivalent of Java's OuterScope.this
syntax? example :
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 } } } }
apply accepts an instance as the receiver while with requires an instance to be passed as an argument. In both cases, the instance will become this within a block. apply returns the receiver and with returns a result of the last expression within its block.
Used in Android development, Kotlin provides a unique feature known as scope functions, however, many developers run into some difficulty when dealing with these functions. As an Android mobile developer, it is important to have a full grasp of this concept, which is a crucial part of application development.
In certain computer programming languages, the Elvis operator ?: is a binary operator that returns its first operand if that operand is true , and otherwise evaluates and returns its second operand.
Kotlin “scope functions” are functions that allow for changing the scope, or the range, of a variable. There are five such functions included in the Kotlin standard library: apply , run , with , let , and also . In that example, we used run to create a smaller scope for inside .
this@MyClass
JFYI: the same syntax for access to receiver of extension function:
fun MyClass.foo() { // in some nested thing: this@foo //... }
Kotlin Reference: This expressions
in my case i accessed it like : 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() } } }
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