preface

Hello, brothers. After learning and mastering the knowledge in the previous three chapters, I believe I am familiar with Kotlin code. 😬😬😬😬😬😬😬😬😬😬 Welcome to the fourth article in Kotlin’s easy to understand series — Extension functions and operator overloading, Infix functions on the road, guys GO GO GO ~ (funny)

1: extension function

First we need to understand what an extension function is. An extension function is the ability to open a class and add new functions to it without modifying the source code of the class. Adding a new function to a class without modifying the source code? Born as a Java android code animals you have heard such a funny thing, here we take a look at exactly how to do We first to implement a function: a string may contain Numbers, letters, and special symbols such as characters, now we look forward to statistics the number of letters in the string, realize the function code is as follows:

object StringUtils {
    fun lettersCount(str: String): Int {
        var count = 0
        for (char in str) {
            if (char.isLetter()) {
                count++
            }
        }
        return count
    }
}
Copy the code

Now let’s see how lettersCount() is added to the String class using an extension function. Here’s the syntax for defining the extension function:

fun ClassName.MethodName(param1:Int,param2:Int):Int{
  return 0
}
Copy the code

To define an extension function, you simply precede the function name with a ClassName, as opposed to a normal function. The grammatical structure of, Now we’re going to try to add an extension function to the String class. First we’re going to create a File called kotlin.kt. Please note that in the previous article we emphasized that.kt, or File, is used to create extension functions and top-level functions In general, it is recommended to create a.kt file for the class to which you want to add extension functions. Of course, extension functions can also be defined in the existing class. It is not necessary to create a new file, but it is best to define a top-level function, so that it can be used globally. The String code looks like this:

fun String.lettersCount(): Int {
    var count = 0
    for (char in this) {
        if (char.isLetter()) {
            count++
        }
    }
    return count
}
Copy the code

Note that lettersCount is defined as an extension of the String class, so that the whole code has the String context called as follows:

Val count = "... 123df".lettersCount()Copy the code

Kotlin’s extension functions make your code simpler, richer, and more object-oriented, and Kotlin has a reverse() function that reverses strings, capitalize() function that capitalizes the first letter, and so on, all of those are extension functions that come with Kotlin, You can add extension functions to any class to improve your development efficiency. Kidding, of course, is to pretend 13 😜)…

In addition, we can also use extension functions to simplify the use of Toast

Toast.makeText(context, "This is Toast", Toast.LENGTH_SHORT).show()
Copy the code

Let’s create a new toast.kt file

fun String.showToast(context: Context, duration: Int = Toast.LENGTH_SHORT) {
 Toast.makeText(context, this, duration).show()
}
fun Int.showToast(context: Context, duration: Int = Toast.LENGTH_SHORT) {
 Toast.makeText(context, this, duration).show()
}
Copy the code

The call only needs to:

"This is Toast".showToast(context, Toast.LENGTH_LONG)
Copy the code

2: operator overload

There are many language built-in operators in Java, such as: Kotlin allows us to extend the use of these operators and keywords by overloading all of them and even other keywords. Kotlin allows arbitrary objects to operate, but we also need to consider the practical implications. For example, adding two Student objects doesn’t seem to make sense, But adding two Money objects makes sense

Operator overloading the operator keyword can be implemented by adding the operator keyword before the specified function. Each operator corresponds to a different function. For example, the plus operator corresponds to the plus() function. The minus operator corresponds to the miuns() function, as shown below

Let’s look at the syntax for operator overloading

Class Obj{operator fun plus(Obj :Obj):Obj{// handle logic}}Copy the code

In the preceding syntax structure, the keyword operator and the function name plus are fixed, while the parameters and the return value of the function are self-definable. This means that an object can be added to another object to return a new object. The corresponding call method is as follows

val obj1 = Obj()
val obj2 = Obj()
val obj3 = obj1 + obj2
Copy the code

Obj1 +obj2 will be converted to obj1.plus(obj2) at compile time

data class Money(val value: Int) {
    operator fun plus(money: Money): Int {
        return money.value + value
    }
}
Copy the code
${money1+money2} ${money1+money2} ${money1+money2} ${money1+money2} ${money1+money2Copy the code

Kotlin allows us to multiple overload the same operator so that we can implement Money objects that add numbers directly

data class Money(val value: Int) {
    operator fun plus(money: Money): Int {
        return money.value + value
    }
    operator fun plus(i: Int): Int {
        return value + i
    }
}
Copy the code
${money1 + money2} ${money1 + money2} ${money1 + money2} ${money1 + 1321}")Copy the code

You can also to the further expansion of Money object, such as currency conversion, rounding of the decimal point value, such as other operator overloading using please refer to our syntactic sugar called function expression and the actual contrast figure, if you want to use, refer to just the addition operator overloading to achieve it Please note that, The last syntaxy of ain B is taintaines (a), the order of the a and B objects is reversed. The semantically understandable String class overloads contains, so we can use the following to determine if there is an H String in the Hello String:

if ("hello".contains("he")) {
}
Copy the code

With operator overloading:

if ("he" in "hello") {
}
Copy the code

We implement a function that randomly generates the length of a string as follows:

fun getRandomLenghtString(str: String): String { val n = (1.. 20).random() val builder = StringBuilder() repeat(n) { builder.append(str) } return builder.toString() }Copy the code

Repeat (n) is one of Kotlin’s standard functions meaning that the lambda expression inside can be repeated n times and the idea is to repeat the string passed in n times, wouldn’t it be nice to just repeat the string if we could just write STR * n if we wanted to multiply by a number, We must override the multiplication operator in the String class, but the String class is a system class and we can’t change it. In this case, we can use extension functions to add functions to the String class. We can add functions directly to the string.kt file we just used

operator fun String.times(n: Int): String {
    val build = StringBuilder()
    repeat(n) {
        build.append(this)
    }
    return build.toString()
}
Copy the code

Just to explain the above code, first operator is required for an overloaded operator, and then times is the String corresponding to the multiplication operator. It’s the syntax of the extension function and now a string can be multiplied by a number

    println("${"jingkaiqaq"*3}")
Copy the code

In addition, String’s Kotlin already provides a repeat() function for repeating the String’s n edges, so our function could be written as follows:

operator fun String.times(n: Int)=repeat(n)
Copy the code

With that in mind, we can now change the getRandomLenghtString code

fun getRandomLenghtString(str: String) = str * (1.. 20).random()Copy the code

3: infix function

val map = mapOf("Apple" to 1, "Banana" to 2, "Orange" to 3, "Pear" to 4, "Grape" to 5)
Copy the code

We use a to B key-value pairs in map, including kotlin’s mapof() function. We can implement a to B syntax because Kotlin provides an advanced syntax: The infix function is used to change the syntax of a programming language function call. For example, a to B is equal to a to (b). Here are two examples to learn how to use the infix function ####3.1: Startswith the startswith function can be used to determine whether a string begins with a specified parameter in the following ways:

If ("Hello Kotlin".startswith ("Hello")) {// Handle specific logic}Copy the code

We’ll use a more readable syntax to express this code. Create a new infix function and write the following code:

infix fun String.beginsWith(prefix: String) = startsWith(prefix)
Copy the code

Let’s create the beginWith function using the infix function above: as shown below

If ("Hello Kotlin" beginsWith "Hello") {// Handle specific logic}Copy the code

The Infix function allows us to write programs with a more English-like syntax by removing computer-specific syntax such as decimals and parentheses from function calls, making the code more readable

Because of the special syntax of the infix function sugar format, there are two strict idle: 1. The Infix function can not be defined as the top-level function, it must be a member function of a class, can be defined in the way of extension function, 2

Let’s look at a more complicated example:

Val list = listOf("Apple", "Banana", "Orange", "Pear", "Grape") if (list.contains("Banana")) {// Handle specific logic}Copy the code

We can still modify it using the infix function

infix fun <T> Collection<T>.has(element: T) = contains(element)
Copy the code

As you can see, we added an extension function to the Collection interface. This is because Collection is the general interface for all Java and Kotlin collections, so we added a has function to Collection, Now we can use the following syntax to determine if there is a value in the set:

Val list = listOf("Apple", "Banana", "Orange", "Pear", "Grape") if (list has "Banana") {Copy the code

Oh, extension functions and operator overloading, infix function, have you felt Kotlin syntax is very interesting, through these interesting syntax can ruthlessly install 13

Next article we are going to learn Kotlin in the most classic knowledge – high order function, brother hold on, the dawn of victory is in front of ~~~ what questions welcome message point out 😜😜😜😜😜😜😜😜😜😜