Language Elements

Data Types

Kotlin Nullable Types

Extension Functions

Lambda Functions

Object Oriented Kotlin

Data Classes

Collections

Kotlin Example Codes

Kotlin Interview Questions

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:


Consider Extension function for the Int class.

     fun Int.eightTime() : Int {
    return this * 8
}
   
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.

Consider an extension function for user defined class. A class for calculating volume of sphere can be defined as:

     

 class SphereVolume (val radius: Double){ 

    fun volume(): Double{ 

    return Math. 4/3 *PI * radius * radius; 

    } 

}
 
An extension function to find diameter of sphere can be defined as:
     
    fun SphereVolume.diameter(): Double{ 

        return 2 * Math.radius; 

    } 
 
 
 
   

Copyright © by Zafar Yasin. All rights reserved.