Kotlin series: extended functions and attributes, and kotlin series extended functions

Source: Internet
Author: User

Kotlin series: extended functions and attributes, and kotlin series extended functions

Extended functions and attributes can be added based on existing classes, but these functions and attributes are defined outside the class. Are you curious? Let's take a look.

Extended Functions

Let's use an example to analyze and add a member function to the String class.LastChar, used to obtain the last character of a string. Run the code first.

Kotlin code

package expandfun String.lastChar(): Char = this.get(this.length - 1)

Yes, you are not mistaken. Except for the package Declaration, there is only one line of code. Its definition rules are like this.Name of the class to be extended by fun. Name of the extended method: the returned value of the extended method = the specific implementation of the method. HereThis indicates the object of the class to be extended. Here it is the String object, so it can call all accessible attributes and methods of the String class.
Then we can call our extension method just like calling a common method. There is no difference, just like below.

Call in Kotlin

Import expand. lastChar // note that this is the call code fun main (args: Array  ) {Println ("Kotlin". lastChar ())} 

Before using the function, you must first import the function and then useString. Extension function call.

Calling in Java

import expand.ExpandFunKt;public class Main { public static void main(String[] args) { System.out.println(ExpandFunKt.lastChar("Kotlin")); }}

You also need to import data in Java, except that the imported data is not a function, but a class name created by a file name. Then, call our extension function like a static method and pass the string as a parameter.
Of course, Kotlin is a language that pursues the introduction. The above extension functions can also be omittedThis is like the following.

fun String.lastChar(): Char = get(length - 1)

However, please note that our extension functions cannot destroy the class encapsulation, that is, we cannot access the private and protected attributes of the class during the extension.
Sometimes, the imported functions in Kotlin may have duplicate names, so we can useWhen the as keyword is imported, it is an alias. You can use this alias when calling it, as shown below.

import expand.lastChar as lastfun main(args: Array  ){ println("Kotlin".last())} 
Extension functions cannot be overwritten.

In fact, if you fully understand the above example, you can instantly understand why the extension function cannot be rewritten. Let's take a look at the calling form of extended functions in Java. It actually calls a static method of the class. Here it involves a Java knowledge point,Static functions do not have polymorphism, and static functions cannot be rewritten. Let's write a Java example to illustrate the following.

Java code

// Parent class public class Father {public void say () {System. out. println ("I'm Dad... ") ;}} // Subclass inherits the parent class public class Son extends Father {public void say () {System. out. println (" I am a Son... ");}}

Then we use the following code to test the following:

public class Main { public static void main(String[] args) { Father father = new Father(); father.say(); Son son = new Son(); son.say(); Father obj = new Son(); obj.say(); }}

The output is as follows:

I'm Dad... I am a son... I am a son...

This is the basic knowledge of Java. you have no objection. Let's proceed with the aboveModify the say () methodStatic look, just like below.

Public class Father {public static void say () {System. out. println ("I'm Dad... ") ;}} Public class Son extends Father {public static void say () {System. out. println (" I am a Son... ");}}

Test code

public class Main { public static void main(String[] args) { Father father = new Father(); father.say(); Son son = new Son(); son.say(); Father obj = new Son(); obj.say(); }}

First, the test code above will not run errors, and we may not call static methods like this at ordinary times. This is just to illustrate the problem.
The running result is as follows:

I'm Dad... I am a son... I'm Dad...

Especially the third running result.Static methods do not have polymorphism. If we further discuss the rewriting of common member variables, the cause of polymorphism is that we are usingThe runtime type calls the method we override, while the call of the static method only depends on the static type of this object.
The above rules also apply to Kotlin, it turns out that extended functions do not have polymorphism (in fact, you only need to remember that extended functions are processed as static functions when called in Java, you can understand)
Next we will use Kotlin to reproduce the above scenarios.

Kotlin code

Package kt // parent class open class Father {open fun say () {println ("I'm Dad... ")} Package kt // subclass class Son: Father () {override fun say () {println (" I am a Son... ")}}

The above Code involves a new syntax. First, in Kotlin, all classes areFinal is not inherited and must be added beforeThe open modifier can be inherited. Second, inheritance is no longer usedExtends keyword, but use: At the same time, the subsequent inheritance class is not the write class name, but also the write(), In fact, this is an integral part. This represents the constructor, which will be described in detail later. Note that the method must be rewritten before the function.Override keyword.
Test code

package ktfun main(args: Array  ){ val father1 = Father(); father1.say(); val son = Son(); son.say(); val obj: Father = Son(); obj.say();} 

Output result

I'm Dad... I am a son... I am a son...

Now we start to extend these two classes and extend a function for both classes.SayName (), as shown below.

fun Father.sayName() = println("Father")fun Son.sayName() = println("Son")

Next, let's test whether the extension function has been rewritten, that is, whether it has polymorphism.

val obj2: Father = Son()obj2.sayName()

Output result

Father

Through the above steps, we have verified that the extension function cannot be rewritten.
Finally, if the member function and the extension function of a class have the same method signature (that is, the method declaration is consistent), the member function will be used first.

Extended attributes

After learning extended functions, it is easier to learn extended attributes. Let's talk about the first scenario in the article. We define an extended attribute for the String class.LastChar, as shown below.

val String.lastChar: Char get() = get(length - 1)

Because String is immutable, the attribute declaration here isVal, and because of our extended attributesLastChar cannot be actually in the class, so we cannot assign initial values and initialization to it. Because there is no place to store values, we can only add the getter method to it to let it return values when called.
Of course, if the extension property is for StringBuilder, we can declare the extension propertyVar and add the getter and setter methods for it, as shown below.

var StringBuilder.lastChar: Char get() = get(length - 1) set(value: Char){ this.setCharAt(length - 1, value) }

You may have been unfamiliar with this writing method at the beginning. We will introduce more relevant content in the future.
Let's take a look at how to call it in Kotlin and Java.

// Call import expand. lastCharfun main (args: Array  ) {Val sb = StringBuilder ("abc") sb. lastChar = 'M' println (sb) println (sb. lastChar )} 

Before using it, you must first import it, and then you can use it like using common attributes.

// Call import expand in Java. expandFunKt; public class Main {public static void main (String [] args) {StringBuilder sb = new StringBuilder ("BNM"); ExpandFunKt. setLastChar (sb, 'w'); System. out. println (ExpandFunKt. getLastChar (sb ));}}

When called in Java, the class with extended property code is imported, and the object and value of the extended class need to be passed in when passing parameters, call their geteer and setter methods like static functions.

Conclusion

Kotlin extends functions and attributes to increase code design flexibility. We can expand and modify existing classes and customize our own classes, this greatly facilitates the Java interoperability of Kotlin.

Related Article

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.