Extensions

4 0 0
                                        

extensions - is the term use when you want to add a function or a property from a class or an interface without extending them. It means you want to add a regular function for example in an interface but you do this outside the interface and you won't be extending the interface or using the colon : which is the equivalent of extend in java.

syntax: function extensions

fun ClassName.methodName(){

    // statement

}


==================

fun main(){

    val str: String = ""

    str.hello("Goddess")

}

fun String.hello(name: String){

     println("Hello! I'm $name. Welcome to kotlin world!")

}

==================

Result:

Hello! I'm Goddess. Welcome to kotlin world!

Note

1. We add a function hello in the String class. But this hello function is not part of the member of the String class. It is just one of those callable functions of String class but not a member of the class since members are those within the class itself. So, in case, there is a conflict, the member always wins.

2. Extensions can be called with a null receiver type.

===================

fun main(){

    val str: String? = null

    str.hell0("Goddess")

    String.yourCompanion("As the class companion, I hereby declare...")

}

fun String?.hello(name: String){

    if(this == null){

        println("Hello! I'm android 99. And you are?")

    }else {

        println("Hello! I'm $name. Welcome to Kotlin world!")

    }

}

fun String.Companion.yourCompanion(message: String){

    println("message: $message")

}

===================

Result:

Hello! I'm android 99. And you are?

message: As the class companion, I hereby declare...


3. Extensions on properties is allowed but you need to provide an explicit getters and setters on the property since initializers are not allowed.

4. If the class has a companion object, you can use extensions in the companion of that class but during invocation, you have to use the class name and not the object. Just like the example above.

Terms: (Declaring an extension of one class into another class)

1. Implicit receiver - It is an implicit object. It means you do not need to specify the object. You can call one of the member of the class without specifying the object.

Kotlin ProgrammingWhere stories live. Discover now