Extension Properties

Not only can you create extension functions, but you can create extension properties as well! The resulting syntax resembles a combination of extension functions and custom property accessors.

Recapping Extension Functions

We saw extension functions earlier in the book. You can use them to add functions to existing classes, including classes that you did not create:

private val EMAIL_REGEX = Regex("^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+[.]+[a-zA-Z0-9-.]+(\s)*")

fun String.isValidEmail() = EMAIL_REGEX.matches(this)

fun main() {
  println("martians-so-do-not-exist@commonsware.com".isValidEmail())
  println("this is not an email address".isValidEmail())
}

From a declaration standpoint, rather than a simple function name, the declaration uses ClassName.functionName(), where ClassName is the class that you are extending with the extension function and functionName is the name of the function that you are adding.

As noted in that earlier chapter, though, extension functions cannot add properties to a class.


Prev Table of Contents Next

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