Kotlin extension

Kotlin can extend the new functionality of a class without having to inherit the class or use design patterns like decorator. This is done through special declarations called extensions. For example, you can write a new function for a class from a third-party library that you cannot modify. This new function can be called using normal methods just like the original one. This mechanism is called extension functions. In addition, there are extension attributes that allow you to add new attributes to an existing class.

Use summary: Extensions are a great way to solve the problem of helper classes that abound in Java.

This article mainly lists my own learning summary, please refer to kotlin official Documentation Chinese translation site for detailed introduction.

1. The extension itself does not actually modify the target class, that is, it does not insert new properties or methods into the target class

The extension function simply automatically generates a function with the current object. When we call the extension function in Kotlin, the compiler will call the auto-generated function and pass in the current object.

2. The resolution of extension functions is distributed statically rather than dynamically, that is, there is no support for polymorphism, and calls depend only on the declared type of the object

The call is determined by the declared type of the object, not the actual type of the object.

Ex. :

open class A

class B: A(a)fun A.a(a) = "a"
fun B.a(a) = "b"

fun print(a: A){
    println(a.a())
}

fun main(args: array<String>){
    print(A())
    print(B())
}
Copy the code

Print result:

a
a
Copy the code

3. An extension function can have the same name as an existing function, but the existing function has a higher priority when invoked

The meaning is clear: the original function of an extension class can have the same name as the extension function, but when a function with the same name is called, the original function is actually called.

Ex. :

open class A{
    a(){
        println("A's method A")
    }
}

fun A.a(){
     println("Extension of A method A")
}

fun print(){
    println(A().a())
}

fun main(args: array<String>){
    print()
}
Copy the code

Print result:

A method ACopy the code

4. Extension functions can overload existing functions

Building on the third point, we can extend functions with the same name, but in an overloaded way, so that calls to methods with the same name have complementary effects.

Ex. :

open class A{
    a(){
        println("A's method A")}}fun A.a(c: Int){
     println("Extension of A method A")}fun print(a){
    println(A().a(1))}fun main(args: array<String>){
    print()
}
Copy the code

Print result:

Extension method A of ACopy the code

5. Nullable types can also be added to extension functions

Ex. :

funAny? .toString (a): String {
	if(null= =this) {returnnull"}return toString()
}
Copy the code

Description:

The object handled by this extension method is a nullable arbitrary type (Any is the root type in Kotlin), this extension is allowed, and the current example addresses the handling of general nullable objects calling toString().

6. Companion objects can also be extended

Ex. :

class MyClass {
    companion object{}// Will be called "Companion"
}

fun MyClass.Companion.printCompanion(a) { println("companion")}fun main(a) {
    MyClass.printCompanion()
}
Copy the code

Description:

The extension of the associated object is much like a normal class, except that it is called in connection with the class that accompanies it. The purpose of the extension method of the companion object is not currently thought of, but perhaps it can be used for general handling when a page jumps to startActivity?

7. Extended scope

Extension functions can be defined as top level functions (common), scoped at the package level. It can also be defined in a class, and when defined in a class can be an extension function of the current class or another class, the scope of the extension function is the current class, generally do not want to expose extension functions can be used in this way.

Note:

Methods in this class can be called when extension functions of other classes are generated in this class. In addition, the method name of this class can be the same as the name of the extension function generated by other classes in this class. If the two names conflict, the extension receiver has the highest priority.

8. Extended properties

The extension attribute is relatively simple, and the extension function use method is basically the same, do not repeat here.