Sobes.tech
Junior

What is the difference between regular and extension methods in Kotlin?

sobes.tech AI

Answer from AI

A regular method is a function declared inside a class.

An extension method is a function declared outside the class but acts as if it were a member of the class. When declaring an extension method, the name of the receiver class to which it applies is specified.

// Regular method
class MyClass {
    fun myMethod() {
        // method implementation
    }
}

// Extension method
fun String.removeVowels(): String {
    // method implementation
}

fun main() {
    val myObject = MyClass()
    myObject.myMethod() // Call to a regular method

    val myString = "Hello"
    val stringWithoutVowels = myString.removeVowels() // Call to an extension method
}

Key differences:

  • Declaration: Regular methods are declared inside a class, extension methods are outside.
  • Access to class members: Regular methods have direct access to private and protected members of the class. Extension methods do not have direct access to private and protected members.
  • this: In a regular method, this refers to the instance of the class in which the method is declared. In an extension method, this refers to the instance of the receiver object for which the extension is called.
  • Inheritance: Regular methods can be overridden in subclasses. Extension methods are not inherited and cannot be overridden.
  • Implementation: Regular methods are part of the class implementation. Extension methods are implemented separately and do not modify the original class.

Extension methods are useful for adding functionality to existing classes without modifying them, for example, to classes from third-party libraries or the Kotlin standard library.