Extension Functions are used to extend Kotlin class with new functionalities without inheriting the class or extending itby using some design pattern (such as Decorator). An extension function is thus extending the class without making any change inside it, as it is defined outside the class.
Features of Kotlin Extension Functions:
- New extension functions are callable from within the class by dot-notation on variables of that type.
- Extension functions are allowed not only for user-defined classes but also for library classes. They are added to library class, similar way as for user-defined classes. This allows to extend the platform APIs and third-party classes.
- Similar to extension functions, Kotlin also allows extension properties.
- The extension function can be defined as a nullable receiver type. Such function is called through nullable extension which can be called on a nullable object variable.
- To declare an extension function, its name can be prefixed with a receiver type, i.e. the type being extended or the class name.
- Within an extension function, private or protected properties of a class cannot be extended.
- Using extension function, Kotlin allows to extend final library class (String etc), unlike Java, where such type of classes cannot be extended.
- Any derived classes from base class (used for adding extension function) will also get it, and can also override the extension function.
Consider Extension function for the Int class.
Int instance will now have an additional function that returns eight time its current value. Keyword this allows to access the instance of the object.fun Int.eightTime() : Int { return this * 8 }
Consider an extension function for user defined class. A class for calculating volume of sphere can be defined as:
An extension function to find diameter of sphere can be defined as:class SphereVolume (val radius: Double){ fun volume(): Double{ return Math. 4/3 *PI * radius * radius; } }
fun SphereVolume.diameter(): Double{ return 2 * Math.radius; }