this@MainActivity vs MainActivity@this in kotlin
Asked Answered
E

2

5

As you may see that

this@MainActivity or MainActivity@this

is valid while starting activity in kotlin. I tried to find out answer but I did not found anything. Can anyone know about exact difference of it and which one valid ? Why it allowed both ?

Elwina answered 9/1, 2019 at 8:23 Comment(1)
MainActivity@this not valid in my sideGoods
G
9

According to Kotlin's Grammar documentation,

MainActivity@this is just a label for this with the name "MainActivity". You can set whatever label you want.

this@MainActivity is an actual reference of this from MainActivity

Hope I make it clear.

Gott answered 9/1, 2019 at 8:30 Comment(2)
Thank you. Intent(this@MainActivity, SettingActivity::class.java) and Intent(MainActivity@this, SettingActivity::class.java) both are valid and working fine. Is there any reason or what statement is same as MainActivity.class and this within MainActivity.Elwina
You might want to read about it here #3434541Gott
A
4

this@MainActivity - it is a reference to current MainActivity instance.

MainActivity@this - it is definition of a name of the label, i.e. MainActivity.

More info about labels.

Arrogance answered 9/1, 2019 at 8:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.