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.
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.
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.
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.
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).
SignInActivity@this means SignInActivity.this (Java) this@SignInActivity means - using the SignInActivity context instead a local context (usually is in closures).
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@
}
}
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