Sobes.tech
Junior

What are extension functions in Kotlin?

sobes.tech AI

Answer from AI

Extension functions are functions that allow adding new functionality to existing classes without modifying their source code and without resorting to inheritance.

They are declared outside the class and are attached to it using the syntax <ClassName>.function<Parameters>. Inside an extension function, this refers to the instance of the class on which it is called.

Example:

// Declaring an extension function for the String class
fun String.addGreeting(): String {
    return "Hello, $this!"
}

fun main() {
    val name = "World"
    // Calling the extension function
    println(name.addGreeting()) // Outputs "Hello, World!"
}

Main advantages:

  • Code cleanliness: No need to create utility classes with static methods or inherit classes just to add functionality.
  • Readability: Calls to extension functions look like regular class methods.
  • Modularity: Functionality can be added in the local scope.

Limitations:

  • Extension functions do not have access to private or protected members of the class.
  • In case of a conflict between a class method and an extension function with the same signature, the class method takes precedence.
What are extension functions in Kotlin? — Kotlin - sobes.tech