10 Expansion of Kotlin learning

Source: Internet
Author: User
Tags class definition
Kotlin Extension

Kotlin can extend the properties and methods of a class and do not need to inherit.
An extension is a static behavior that does not have any effect on the extended class code itself.

Extension of the class, what a ghost. Anyway, I have never seen Java, the following look at the expansion of the Kotlin bar. I. Extension methods

is to add a method. 1. Extension methods can add new methods to existing classes, do not modify the original class, and extend the method definition form:

Fun Receivertype.functionname (params) {
   //body Method
}
Receivertype: Represents the recipient of the method, which is the object of the method extension, that is, the class name. functionname: The name of the extension method params: An argument to extend a method that can be null

Note that the above three are not keywords, is a symbolic noun. 2. The following example extends the User class:

Class User (Var name:string)

/** extension method **/
Fun User.print () {
    Print (user name $name)
}

fun Main (arg :array<string>) {
    var user = user ("Runoob")
    user. Print ()
}
instance execution output is:
User name Runoob
3. The following code adds a swap method to Mutablelist:
Package Hello                      //optional  Baotou
//extension method swap, swap values in different locations
fun Mutablelist<int>.swap (Index1:int, Index2:int {
    val tmp = this[index1]     //This  pair should list
    this[index1] = This[index2]
    this[index2] = tmp
}

Fun Main (args:array<string>) {

    val L = mutablelistof (1, 2, 3)
     println (l.tostring ())
    //Location 0 and The value of 2 is interchangeable
    l.swap (0, 2)//' Swap () ' method ' This ' will point to the value of ' L '
    println (l.tostring ())
}
instance execution output is:
[1, 2, 3]
[3, 2, 1]

The above mutablelist is the collection class of the system, although there is no this class in Java, but there are many similar collection classes.
The This keyword refers to the receiver object (receiver object) (the object instance specified before the dot number when the extension method is invoked). Which is the object of the class itself. two. The extension method is statically parsed by 1. The extension method is statically parsed .

is not a virtual member of the receiver type, when the extension method is invoked, which method is called, determined by the object expression of the calling method, not by the dynamic type:

Open Class C  //definition can be inherited Class C class

D:c ()  //Definition class D

fun C.foo () = "C"   //extension method foo

fun d.foo () = "D"   Extension method foo

fun Printfoo (c:c) {
    println (C.foo ())  //Type is Class C
}

fun Printfoo (d:d) {
    println (d. Foo ())  //type is D class
}

Fun Main (arg:array<string>) {
    Printfoo (d ())//print D
    printfoo (C ())// Print C
}
instance execution output is:
D
C

Here the subclass and the parent class method are duplicated, the extension methods are all added later, the method overrides will not occur, the subclass object executes the subclass method, and the parent object executes the method of the parent class. 2. If the extension method and the member method are consistent, the member method is used preferentially when the method is used.

Class C {
    fun foo () {println (member method)}
}

fun C.foo () {println (extension method)}

fun Main (Arg:array<strin g>) {
    var c = C ()
    C.foo ()
}
instance execution output is:
Member Methods

Here if the original method of the class is the same as the extension method, the extension method is useless. three. Extend an empty object 1. Within the extension method, you can use this to determine whether the recipient is null, so that the extension method can be invoked even if the receiver is null.

For example:

Fun any? ToString (): String {
    if (this = = null) return "NULL"
    //NULL detection, "This" is automatically converted to a non-null type, so the following toString ()
    //resolves to the any class Member method return
    toString ()
}
Fun Main (arg:array<string>) {
    var t = null
    println (t.tostring ())

    var t2 = 505
    println (t2.tostring ())
}

The above looks like a very hanging, incredibly extended system of the class any, similar to Java object.

If you replace the System class method, other places do not pay attention, there will be no bugs. So it is recommended to change the method of system class less. instance execution output is:

Null
505
2. Extended Properties

In addition to methods, Kotlin also supports attributes to extend properties:

Val <T> list<t>.lastindex:int Get
    () = Size-1

Extended properties allow definition in a class or Kotlin file and are not allowed in a method.
Initialize property because the property does not have a backend field (backing field), it is not allowed to be initialized and can only be defined by an explicitly supplied Getter/setter.

Val foo.bar = 1//Error: Extended properties cannot have an initializer

Extended attributes can only be declared as Val. Four. Extension of associated objects If a class definition has an associated object, you can also define extension methods and attributes for the associated object.

The companion object passes the "class name." Form invokes the associated object, the associated object declares an extension method that is invoked by using the class name qualifier:

Class MyClass {
    companion object {}  //will be called "companion"
}

Fun MyClass.Companion.foo () {    // Extend the method println (the companion object
    's extension method)
}

val MyClass.Companion.no:Int    //To the companion object to extend the Property Get
    () = 10

Fun Main (args:array<string>) {   //Call the associated object's properties and methods
    println ("no:${myclass.no}")
    Myclass.foo ()
}

Note that the above companion is the keyword, companion is also the keyword, and their use can not be arbitrarily mistaken. instance execution output is:

extension method of No:10 adjoint object
Five. Scope of expansion

Typically, the extension method or attribute is defined under the top-level package:

Package Foo.bar

To use an extension other than the defined package, import the extended method name using the import:

Package Com.example.usage Import

Foo.bar.goo//Import all the Goo extensions//imports foo.bar.*/All Foo.bar   5/>fun usage (baz:baz) {
    Baz.goo ()
}
six. Extended declaration as a member 1. Within a class you can declare extensions for another class.

In this extension, there is a plurality of implied recipients, where an instance of the extension method defines the class as the distribution recipient, while an instance of the target type of the extension method is called an extension recipient.

Class D {  //definition classes D
    Fun Bar () {println ("D Bar")}
}

Class C {  //definition Class C

    fun Baz () {println ("C BA Z ")}

    Fun D.foo () {  //Extending class D Method
        Bar ()   //Calling D.bar
        Baz ()   //Calling C.baz
    }

    Fun Caller (D:D) {
        d.foo ()   //Calling extension method
    }
}

//Test
Fun Main (args:array<string>) {
    val c:c = C ()
    val d:d = d ()
    C.caller (d)

}
instance execution output is:
D Bar
C Baz

Within class C, an extension of Class D is created.
At this point, C becomes the distribution recipient, and D is the extended recipient.
From the example above, it is clear that in the extension method, you can call the member method that distributes the receiver. 2. If you are calling a method that exists in both the distribution recipient and the extended receiver, the extension recipient takes precedence, and you can use the qualified this syntax to refer to the members of the distribution receiver.

Class D {
    fun bar () {println ("D Bar")}
}

class C {
    Fun bar () {println ("C Bar")}  //is the same name as bar in Class D C8/>fun D.foo () {
        bar ()         //Call D.bar (), extended receiver Priority
        This@C.bar ()  //Call C.bar ()
    }

    Fun caller (D: d) {
        D.foo ()   //Calling extension method
    }
}

fun Main (args:array<string>) {
    val c:c = C ()
    Val D : D = d ()
    C.caller (d)

}

This is similar to Java, if the properties of the method and the properties of the class conflict, to invoke the class's properties to use this declaration. instance execution output is:

D Bar
C Bar
3. An extension method defined as a member can be declared open and overridden in a subclass.

That is, during the distribution of such extension methods, the distribution recipient is virtual, but still static for the extended recipient.

Open Class D {//definition Class D
} class

D1:d () {//Definition class D1
}

Open Class C {//definition Class C
    open Fun D.foo () {//Extended Class D, Add method Foo
        println ("D.foo in C")
    }

    Open Fun D1.foo () {//Extension class D1, adding method foo
        println ("D1.foo in C")
    }

    Fun Caller (D:D) {
        d.foo ()   //Calling extension methods
    }
}

class C1:c () {//Definition class C1 override fun D.foo
    () {  / /overriding extension methods for class D
        println ("D.foo in C1")
    }

    override Fun D1.foo () {//overriding extension methods for class D1
        println ("D1.foo in C1") c22/>}

//Test
Fun Main (args:array<string>) {
    C (). Caller (D ())   /output "D.foo in C"
    C1 (). Caller (D ())  /output "D.foo in C1"--distribution recipient virtual Resolution
    C (). Caller (D1 ())  /output "D.foo in C"--extended receiver static resolution

}

The above procedure can look at the detail point.
Note that the caller method is the parent class C method. instance execution output is:

D.foo in C
d.foo into C1
D.foo in C

The extension of the

Kotlin, a wonderful thing, was learned here.
Interested can test online, as many classes can be tested online.
https://blog.csdn.net/wenzhi20102321/article/details/79859347 : While young, multi-activity

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.