Language Elements

Data Types

Kotlin Classes

Kotlin Operators

Kotlin Nullable Types

Extension Functions

Kotlin Functional

Lambda Functions

Object Oriented Kotlin

Data Classes

Coroutines

Collections

Delegation

Lateinit and Lazy Initialization

Scope Functions

Kotlin Key Words

Kotlin Example Codes

Kotlin Interview Questions

Extension Functions in Kotlin allow adding new functionality to existing classes, including library classes, without inheritance or modifying their source code. This eliminates the need for traditional design patterns like the Decorator, which typically requires wrapping objects to extend behavior.

Features of Kotlin Extension Functions:

When to use Inheritance not Extension Functions

To access or modify the private or protected members of a class, extension functions are not the solution. Use inheritance to create a subclass that has the necessary access privileges.

How extension functions are built below the hood

  1. Compiled as Static Functions: When a Kotlin extension function is written, the compiler translates it into a static function in the generated code.
  2. Receiver as First Parameter: This static function takes the object on which the extension function is called (the "receiver") as its first parameter.

Kotlin Extension Function Examples

Example 1: Extending Primitive Type (Int)

// Extends Int with a new multiplication operation
fun Int.eightTimes(): Int = this * 8  // 'this' refers to the Int receiver

fun main() {
    val number = 5
    println(number.eightTimes())  // Output: 40
    println(10.eightTimes())      // Output: 80
}

Note: Extension functions work on both variables and literals.

Example 2: Extending a Custom Class

class Sphere(val radius: Double) {
    fun volume(): Double = (4.0 / 3) * Math.PI * radius.pow(3)
}

// Extension adds diameter calculation to Sphere class
fun Sphere.diameter(): Double = 2 * radius  // Implicit 'this' access

// Another extension demonstrating receiver access
fun Sphere.surfaceArea(): Double = 4 * Math.PI * radius.pow(2)

fun main() {
    val unitSphere = Sphere(1.0)
    println("Volume: ${unitSphere.volume()}")       // 4.188...
    println("Diameter: ${unitSphere.diameter()}")  // 2.0
    println("Surface Area: ${unitSphere.surfaceArea()}")  // 12.566...
}

Key Notes:


Copyright © by Zafar Yasin. All rights reserved.