Kotlin learning (6) extension functions and attributes

In Java, we often use the tools such as StringUtil, DateUtil like to write code relatively lengthy.
For example, we want to write a utility class to get the first letter and the last letter of a string, we must first write a utility class and then defined the two methods. Because the String class is not to add their own custom methods.

In Kotlin is not the same, natural decorative pattern, makes the code more concise.

1. Spread Function

1.1 String class to extend the two functions

  fun String.firstChar(): String {
        if (this.isEmpty()) return ""
        return this[0].toString()
    }

  fun String.lastChar(): String {
        if (this.isEmpty()) return ""
        return this[this.length - 1].toString()
    }
    
//调用:
println("abc".firstChar())   //a
println("abc".lastChar())    //c

//如果在其它package路径下面,则需要调用import导入扩展函数
import com.rikka.kotlin.firstChar
import com.rikka.kotlin.lastChar

1.2 List to expand a filter function
if we customize a filter function in koltin, it should be written like this:

 fun <T> List<T>.filter(predicate: (T) -> Boolean): MutableList<T> {
        val result = ArrayList<T>()
        this.forEach {
            if (predicate(it)) {
                result.add(it)
            }
        }
        return result
    }
//调用
val result = list.filter{
     it % 2 == 1
}
println(result)

Use fun <类型参数> 目标类型.扩展函数名(函数入参): 函数返回类型to expand

2. Extended Attributes

In addition to extending the function of a class, the class attribute may be extended.
For example, we give MutableList two extended attributes: firstElement and in lastElement, code is as follows:

 private var <T> MutableList<T>.firstElement: T
        get() {
            return this[0]
        }
        set(value) {
            this[0] = value
        }
    var <T> MutableList<T>.lastElement: T
        get() {
            return this[this.size - 1]
        }
        set(vale) {
            this[this.size - 1] = vale
        }

//使用:
println(list.firstElement)
println(list.lastElement)
list.firstElement = x
list.lastElement = y

Syntax is as follows:

var <类型参数> 目标类型.扩展函数名:扩展函数的类型
  get(){
      //getter
  }
  set()}{
      //setter
  }

3. Expand keywords

In front of the List to achieve extended functions filter (), the use of a this keyword

this.forEach{
   if(predicate(it)){
      result.add(it)
   }
}

Here this refers to the recipient of the object, that is invoked when the extension functions specified before the dot. "" Object instance.
To show the current function of the recipient, Kotlin use this expression:

  • In the class member functions, this refers to the current object instance of this class
  • In the extended function, when this function is invoked on behalf of the dot in the left passed receiver parameters
  • If this is not a qualifier, then it contains the current code innermost range.
Published 248 original articles · won praise 99 · Views 100,000 +

Guess you like

Origin blog.csdn.net/rikkatheworld/article/details/102920559