Software Development

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.

[wp_ad_camp_1]

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.

[wp_ad_camp_2]

Sample Usage

Output

[wp_ad_camp_3]

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.

[wp_ad_camp_4]

References

[wp_ad_camp_5]

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like