0

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?

Brandon Xia
  • 407
  • 3
  • 19
  • 3
    You can always omit `this` anywhere there isn't ambiguity, not just in extension functions. `this` is only necessary when you need to distinguish members with matching names, like in a function where a parameter name matches a name in the class containing the function. – Tenfour04 Aug 05 '20 at 20:01

1 Answers1

1

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.

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
  • "When you call a member function on this, you can skip the this." Or an extension function, or access a property, or an inner class... – Alexey Romanov Aug 06 '20 at 06:28