Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 735
viz Avatar asked Dec 04 '17 04:12

viz


People also ask

Which line can be marked with label in Kotlin?

Any expression in Kotlin may be marked with a label. Labels have the form of an identifier followed by the @ sign, such as abc@ or fooBar@ . To label an expression, just add a label in front of it.

What does ?: Mean in Kotlin?

This is a binary expression that returns the first operand when the expression value is True and it returns the second operand when the expression value is False. Generally, the Elvis operator is denoted using "?:", the syntax looks like − First operand ?: Second operand.

What is difference between it and this in Kotlin?

While scope like : let, also, to call the methods of the object, we can call them using the "it" as it has scope of the class win which this method is written.

What is Colon in Kotlin?

The colon : always indicates the declaration of a type in Kotlin. An expression is a part of your code that can return a value. A statement is a block of code that returns no value. In Kotlin, all functions return a value, even if no return type is provided (the default return type is Unit).


2 Answers

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

like image 189
Maxim Firsoff Avatar answered Sep 28 '22 01:09

Maxim Firsoff


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@
   }
}
like image 37
Zimin Byun Avatar answered Sep 28 '22 01:09

Zimin Byun