Sobes.tech
Junior

What are extensions in the Kotlin programming language?

sobes.tech AI

Answer from AI

Extensions in Kotlin allow adding new functions or properties to existing classes without inheritance or using decorators.

Main concepts:

  • Extension Functions: Add new methods to classes.

    // Defining an extension function
    fun String.removeWhitespaces(): String {
        return this.filter { it.isWhitespace().not() }
    }
    
    // Using the extension function
    val myString = " Hello World "
    val cleanedString = myString.removeWhitespaces() // cleanedString will be "HelloWorld"
    

    The this keyword inside an extension function refers to the object the extension is called on (in the example above, myString).

  • Extension Properties: Allow adding new properties to classes, but cannot have state, meaning they cannot store data. They are computed each time they are accessed.

    // Defining an extension property
    val <T> List<T>.lastIndex: Int
        get() = size - 1
    
    // Using the extension property
    val myList = listOf(1, 2, 3)
    val indexLast = myList.lastIndex // indexLast will be 2
    

    Extension properties must have a getter. Setter is optional.

Features:

  • Static dispatch: The call to an extension is determined by the variable's type, not the object's runtime type. This differs from virtual methods in object-oriented programming.

    open class Parent
    class Child : Parent()
    
    fun Parent.printType() = println("Parent")
    fun Child.printType() = println("Child")
    
    val p: Parent = Child()
    p.printType() // Will print "Parent" because the variable 'p' is of type Parent
    
  • Private and protected members: Extensions cannot access private or protected members of the class they extend.

  • Companion Object Extensions: You can extend companion objects of classes.

    class MyClass {
        companion object {
            fun create() = MyClass()
        }
    }
    
    fun MyClass.Companion.printName() = println("MyClass Companion")
    
    MyClass.printName() // Will print "MyClass Companion"
    
  • Visibility scope: Extensions must be declared in a file and then imported for use in other files.

Extensions are a powerful tool for creating readable and flexible code, allowing adding functionality to classes from third-party libraries without modifying their source code.