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?
() 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?.
In Kotlin, the “this” keyword allows us to refer to the instance of a class whose function we happen to be running.
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.
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.
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.
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