Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the `this@classname` mean in Kotlin?

I am making a custom view for Android. I am going to clone the layout by calling clone (this), but it shows error, when I use clone (this@mycustomclassname), it works.

It's still confused. Anyone knows the meaning of this@classname in kotlin?

like image 834
Li Jin Avatar asked May 14 '19 13:05

Li Jin


People also ask

What is ClassName () in Kotlin?

() mean in Kotlin? It is called a function literal (or lambda) with receiver. An example to try to explain the same: data class Person(val name: String) fun getPrefixSafely( prefixLength: Int, person: Person?, getPrefix: Person.(Int) -> String): String { if (person?. name?.

What is this () in Kotlin?

In Kotlin, the “this” keyword allows us to refer to the instance of a class whose function we happen to be running.

What is it and this in Kotlin?

it is only relevant inside a lambda with a single parameter. It is the default name for a single parameter and is a shorthand that allows you to omit naming the single parameter. A function that is declared this way might look like this: (String) -> Unit. In a lambda, this is the receiver argument.

What does :: means in Kotlin?

Android API only accepts Java classes, that's why you need to pass a Java class. IntroAndLang::class returns a KClass (a Kotlin class), then . java returns the Java class. Note that all Kotlin classes are compiled to Java classes ( . class binaries) in the end.


1 Answers

This is a qualified this. You can access this from an outer scope.

As this can mean different things (part the referenced page):

To denote the current receiver, we use this expressions:

  • In a member of a class, this refers to the current object of that class.
  • In an extension function or a function literal with receiver this denotes the receiver parameter that is passed on the left-hand side of a dot.
like image 103
DVarga Avatar answered Sep 18 '22 14:09

DVarga