Position of `@` label in Kotlin when denoting receiver with `this`
Asked Answered
W

2

10

I am a newbie in Kotlin. I am curious about the difference of labeled this in Kotlin with prefix @ or postfix @.

I have just seen a code which writes SignInActivity@this, which seems to work exactly same as this@SignInActivity.

Are these two exactly the same thing? If not, what is the difference between the two?

I was trying to do some research on *@this form, but I couldn't find any reference on it. All I could find was this official doc which demonstrates this@*. It will be nice if anybody could share me with the correct reference I should go to.

Wheelock answered 4/12, 2017 at 4:37 Comment(2)
This seems valid, interestinglyLeff
@1blustone it really doesWheelock
F
7

SignInActivity@ this is just another expression for this, with the functionality of defining an unnecessary label called SignInActivity(which has nothing to do with actual class name) for this.

According to Kotlin grammar documentation:

labelReference (used by atomicExpression, jump)
   : "@" ++ LabelName
   ;
labelDefinition (used by prefixUnaryOperation, annotatedLambda)
  : LabelName ++ "@"
  ;

hello@ is just a label with the name "hello" (for Returns and Jumps) ,

whereas @hello is a reference for the labeled loop or block.

These expressions combined can be used as below:

loop@ for (i in 1..100) {
    for (j in 1..100) {
        if (...) break@loop //jump to loop@
   }
}
Fanatical answered 4/12, 2017 at 10:55 Comment(1)
Great answer! Thanks a lot. So it was only a superstition. lol.Wheelock
R
5

SignInActivity@this means SignInActivity.this (Java) this@SignInActivity means - using the SignInActivity context instead a local context (usually is in closures).

Rowles answered 4/12, 2017 at 8:57 Comment(4)
Hey, thanks for the answer. After some testing, I'm kind of convinced that what you are saying is actually correct. But could you provide me with some reference or spec to elaborate? Because when I see kotlinlang.org/docs/reference/… which demonstrates the usage of @, I don't find any proof that @ can used as a postfix as in SignInActivity@ this.Wheelock
The link you provided actually lists that @ can reference a 'this' expression from an outer scope.Rickey
@Rickey Yes, but notice that it's in a form of this@label, not label@thisWheelock
Oh, right, my bad, I just skimmed the original post. It's fascinating that this works too.Rickey

© 2022 - 2024 — McMap. All rights reserved.