Kotlin: useful extension functions

First look at the grammatical structure of the extension function, as follows:

fun ClassName.methodName (param1:Int ,param2:Int) :Int {
    
    
  return 0
}

Compared with defining an ordinary function, defining an extended function only needs to add a ClassName.syntax structure in front of the function name , which means that the function is added to the specified class .

Let's go back and see what is an extension function?

Extended function means that even without modifying the source code of a certain class, you can still open this class and add new functions to the class .

In order to better understand the extension function, let's take the following function as an example.

A string may contain characters such as letters, numbers, and special symbols. Now we want to count the number of letters in the string. How do you achieve this function? If you follow the general programming thinking, most people may write it naturally The following function:

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

Here we first define a StringUtil singleton class, and then define a lettersCount() function in this singleton class, which receives a string parameter. In the lettersCount() method, we use a for-in loop to traverse the string Each character in the string. If the string is a letter, then the counter is incremented by 1, and finally the value of the counter is returned.

  val str = "ABC123xyz!@#"
  val count = StringUtil.lettersCount(str)
  System.out.println(count)

This writing method can definitely work normally, and this is also the most standard implementation thinking in Java programming. But with the extension function, it is different. We can use a more object-oriented thinking to achieve this function, such as changing lettersCount The () function is added to the String class.

Since we want to add an extension function to the String class, we need to create a String.kt file first. Although the file name does not have a fixed requirement, I suggest to add an extension function to which class to define a Kotlin file with the same name, so It is convenient for you to find it later. Of course, the extension function can also be defined in any existing class, and it is not necessary to create a new file. But generally speaking, it is best to define it as a top-level method, so that the extension function can have Global access domain .

By comparison, we can find that we define the lettersCount() method as an extended function of the String class, then the function automatically has the context of the String instance. Therefore, the lettersCount() function no longer needs to receive a string parameter, but Just traverse this directly, because now this represents the string itself.

According to the writing method of the expansion function above, it is written as follows:

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

After defining the extension function, counting the number of letters in a string only needs to write like this:

 val count = "ABC123xyz!@#".lettersCount()

Isn't it amazing? It looks like the lettersCount() method comes with the String class.

Extension functions in many cases make the API more concise, richer, and more object-oriented. Let's take the String class as an example again. This is a final class, and no class can inherit it, which means that its API is only fixed. Those are only those, at least in Java. However, it is different in Kotlin. We can extend any function to the String class to make its API richer.

Of course, the scope of the extension function is not only the String class, you can also add extension functions to any class. Kotlin basically has no restrictions on this. If you can make good use of the extension function, it will greatly improve your Code quality and development efficiency.

Guess you like

Origin blog.csdn.net/gaolh89/article/details/107846848