The Limitations

Extension functions live outside of the classes that they are extending. In the end, extension functions are “syntactic sugar” and are equivalent to a regular top-level function. So, in the case of String.isValidEmail(), the isValidEmail() extension function on String is really no different than a top-level isValidEmail(value: String) function that operated on the supplied String parameter.

As a result, extension functions have no special access to the implementation of the class being extended by the function. In particular, extension functions have no access to private or protected members.

class Something {
  val thisIsPublic = true
  private val thisIsNot = false
}

fun Something.kindaGrabby() = this.thisIsPublic && this.thisIsNot

This code fails with a compile error:

error: cannot access 'thisIsNot': it is private in 'Something'
fun Something.kindaGrabby() = this.thisIsPublic && this.thisIsNot
                                                        ^

Since thisIsNot is private, kindaGrabby() has no access to it.

Extension functions also have no ability to add new properties to the class that they are extending. As a result, extension functions have no ability to store new data. All they can do is manipulate the data that the class already stores.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.