Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

extension
kotlin
communitycreator

What is the extension method in Kotlin?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

We can use the extension functionality in Kotlin to add new functions to a class without inheriting the class.

With the extension mechanism, we can add new functions to a class from a third-party library that we can't modify. The newly added function can be invoked like class methods.

Example

class Greet (){
    fun sayHi(){
        println("hi");
    }
}
fun main(){
    // Create an extension function for a Greet class 
    fun Greet.sayHello(){
        println("hello");
    }
    // Create an object for the Greet class 
    val greet = Greet()
    greet.sayHello()
}
Using the extension function Kotlin

Explanation

  • Lines 1–5: We create a Greet class with a sayHi function.
  • Lines 8–10: We created an extension function, sayHello, for the Greet class.
  • Line 13: We invoked the sayHello extension function.

Note: We can read more about extension functionality here.

RELATED TAGS

extension
kotlin
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring