Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin outer scope

Tags:

kotlin

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             }         }     } } 
like image 948
cdroid Avatar asked Oct 22 '14 08:10

cdroid


People also ask

What is .apply in Kotlin?

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.

What is the scope of Kotlin?

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.

What does ?: Mean in Kotlin?

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.

Can you make a new scope in Kotlin?

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 .


2 Answers

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

like image 53
bashor Avatar answered Oct 11 '22 12:10

bashor


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()         }     } } 
like image 32
Tushar Pandey Avatar answered Oct 11 '22 13:10

Tushar Pandey