Search code examples
kotlinthisextension-function

Do Kotlin Extension Functions declare member variables implicitly?


I have a data class User

data class User(name: String?, email: String?)

and I created an extension function to get the best identifier (name first, then email)

fun User.getBestIdentifier(): String {
    return when {
        !this.name.isNullOrBlank() -> this.name
        !this.email.isNullOrBlank() -> this.email
        else -> ""
}

But I noticed that in my IDE if I get rid of all of the this words, it still compiles and runs. Like:

fun User.getBestIdentifier(): String {
    return when {
        !name.isNullOrBlank() -> name
        !email.isNullOrBlank() -> email
        else -> ""
}

My conclusion was that Kotlin extension functions support member variables implicitly but I am not sure. Does anyone have any documentation of this phenomena or an explanation of why/how it happens?


Solution

  • The docs state:

    The this keyword inside an extension function corresponds to the receiver object.

    In your case, User is the receiver object and thus this refers to exactly that object.

    Another reference can be found on this site which describes the this expression:

    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.

    Further:

    When you call a member function on this, you can skip the this.