Search code examples
kotlinkotlin-extension

Kotlin - Extension for final class


Is it possible to create extension of final classes like String? Like in swift it is possible to add additional methods inside a extension of final class.

For an example - I would like to create a method in String extension which will tell me String have valid length for password.

 val password : String = mEdtPassword!!.getText().toString()

 // how to define haveValidLength method in extension
 val isValid : Boolean = password.haveValidLength()

Note - That example is just for a sake to understand usability of extension, not a real scenario.


Solution

  • yes, you can. Kotin extension method provides the ability to extend a class with new functionality without having to inherit from the class or use any type of design pattern such as Decorator.

    Below is an extension method for a String:

    //  v--- the extension method receiver type
    fun String.at(value: Int) = this[value]
    

    And the extension method code generated as Java below:

    public static char at(String receiver, int value){
        return receiver.charAt(value);
    }
    

    So an extension method in Kotlin is using delegation rather than inheritance.

    Then you can calling an extension method like as its member function as below:

    println("bar".at(1))//println 'a'
    

    You also can write an extension method for the existing extension function, for example:

    fun String.substring(value: Int): String = TODO()
    
    //    v--- throws exception rather than return "ar"
    "bar".substring(1)
    

    But you can't write an extension method for the existing member function, for example:

    operator fun String.get(value: Int): Char = TODO()
    
    //   v--- return 'a' rather than throws an Exception
    val second = "bar"[1]