Extensions in Kotlin

Extensions in Kotlin

In this article, we will learn about extensions and what are the different cases where you can(and should) use them. Before starting, I am supposing that you have a basic understanding of OOPs in any programming language.

Extensions:

We know, whenever we want to override any function or field of a class, then we have to extend that class. But, in Kotlin this thing is more complex because If we want to extend any class then that class should be marked as an Open class. But , what If any library class is not Open…? Here comes the Extensions.

In simple words: We can write function of any other class without having to actually extend it(creating a subclass) by using an extension function. And the function we create will act the same as it is provided by parent class itself.

Note: We can not access private members of extended class as we are creating our extension function outside of that class. And obviously that will also kill the benefit of private things.

In official words: Kotlin provides the ability to extend a class or an interface with new functionality without having to inherit from the class or use design patterns such as Decorator. This is done via special declarations called extensions.

Example: If you want to write a function of String class then we have to extend that class to do so, but String class is not open. So, we can write here an extension function(convert()) and use it whenever we create a string object.

fun main(){
  val strName = "Sagar"
  println(strName.convert())
}

fun String.convert() : String {
    return "Converted String is: $this"
}

You can see this thing will work fine. We can create a string object and use convert function(that we created) on that.

The syntax is very simple, just use class name and dot-notation and after that write your whole function.

But, how is this thing even possible? How, can we write a function of a class without extending it? Well, we are not writing the “function” of the String class here.

Extensions are resolved statically:

Extensions do not actually modify the classes they extend. By defining an extension, you are not inserting new members into a class, only making new functions callable with the dot notation on variables of this type.

What If we are Extending the existing function:

If a class has a member function, and an extension function is defined which has the same receiver type, the same name, and applies to given arguments, the member always wins.

For example:

fun main() {
    class Example {
        fun printFunctionType() { println("Class method") }
    }

    fun Example.printFunctionType() { println("Extension function") }

    Example().printFunctionType()
}

Here, the output will be: “Class method”

Points:

  • The object can be also null. For that write: “String?.convert()

  • You can also override existing function by changing parameters.

  • Use this keyword to access the current object.

  • You can also write generic extension functons.

Extension properties

Kotlin supports extension properties much like it supports functions:

val String.weight : String
    get() = "${this.length} kg"
fun main() {
    print("abs".weight)
}

We can only do this thing be using getter/setters and we can not initialize these fields. Since extensions do not actually insert members into classes, there’s no efficient way for an extension property to have a backing field.

Note on visibility

Extensions utilize the same visibility modifiers as regular functions declared in the same scope would. For example:

  • An extension declared at the top level of a file has access to the other private top-level declarations in the same file.

  • If an extension is declared outside its receiver type, it cannot access the receiver’s private or protected members.

Reference:

I hope you found this helpful. If yes, then do FOLLOW me for more Android-related content.

#androidWithSagar #android #androiddevelopment #androiddev