0

Kotlin – Extension Functions

An Extension Function is a function that is attached to an existing class and are invoked like member functions. For this post, we are using Kotlin 1.1.

Member Functions

In OOP, we have a class and it has member properties and behaviors. A member function is a class’ behavior.

Extension Function

Given the class declaration above, we would create an Extension Function this way:

Note is this example that we are referencing the instance variables make and year. We also invoke a member function from our extension function.

Sample Usage

Output

Extensions are resolved statically

This means that the “attached” function is only available from instances of the specific class the function was attached to. We cannot use these methods polymorphically.

The Codes

The full source codes are listed below. There are 2 files.

References

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert