Kotlin Basics - Extension Functions

Table of contents

1. Understanding

Two, the extension method

1. Extension of common class

2. Extension of generic class

3. Extended properties 

1. Property extension in kotlin

2. Using Koltin's extended attributes in Java

4. Expansion of companion objects

5. Common extension functions

1、run

2、apply

3、let

Six: Case: Extend the findViewById method for Activity

Seven: Case: Four operations


1. Understanding

     Koltin's extension functions enable you to extend a class with new functionality without inheritance. For example, you can create a class that you do not

It can be modified from a class in a third-party library to write an extension. This new function is just like the original function in the original class.

In the same way, it can be called by ordinary methods. In addition, there are attribute extensions, common extension functions.

Two, the extension method

    To extend the method of a class, you only need to add the class name before the function name when the method is declared .

For example: means to extend the method of obtaining the last character of the String class, the method extension of the class should be outside the class body

fun String.lastChar(str:String):Char{



}

1. Extension of common class

fun main() {
    val a :Char=  OpenString().lastChar("abc")
    println(a)
}


fun OpenString.lastChar(str:String):Char{
    if(str.isEmpty()){
        throw Exception("this String an illegal")
    }
    return  str[str.length-1]
}

open class  OpenString{

    fun test(){
        println("test")
    }

}

Use the Kotlin extension in Java to 文件名+Kt.函数名(扩展类的对象,完整的其他参数)call the extension function in Java (equivalent to calling the static method of the tool class), such as in test.java:

public class test {

    public static void main(String[] args) {
        char lastChar = BaseDataTypeKt.lastChar(new OpenString(),"hello world");
        System.out.printf(String.valueOf(lastChar));
    }

}

2. Extension of generic class

fun main() {
    val  list = mutableListOf<String>("android","kotlin","java")
    list.swap(0,1)

    list.forEach {
        println(it)
    }
}

fun <T> MutableList<T>.swap(index: Int,index1: Int){
    val temp:T = this[index1]
    this[index1] = this[index]
    this[index] = temp
}

kotlin
android
java

3. Extended properties 

1. Property extension in kotlin

For example, to find the first character of the String class

fun main() {
    val str = "android"
    println(str.firstChar)

    val array :ArrayList<Int> = arrayListOf(1,2,3,4,5)
    println(array.lastItem)

}


val String.firstChar:Char get() = this[0]

val <T> List<T>.lastItem:T get() = this[size-1]

2. Using Koltin's extended attributes in Java

In Java, to get Kotlin's extended properties, use the class name KT.get extended properties (parameters)

    public static void main(String[] args) {
        char lastChar = BaseDataTypeKt.getFirstChar("hello world");
        System.out.printf(String.valueOf(lastChar));
    }

4. Expansion of companion objects

If a class defines a companion object, it can also extend the properties and methods of the companion object

fun main() {
    val studentA =  Student.search("lisi")
    println(studentA)

    val height = Student.height
    println(height)

}

class Student{
    companion object{

    }
}


fun Student.Companion.search(name:String):String{
    return name
}

val Student.Companion.height:Int get() = 100

lisi
100

5. Common extension functions

1、run

The run function is to extend an instance of a class. In the run method, you can directly access a public instance or method of a class.

What is a public attribute or method is not modified by private/protected. Second, the run method has a return value, and finally

A statement ends, or ends with return.

fun main() {
    val result = test(Tree())
    println("this tree have $result leaf.")
    method(Tree())
}


fun test(tree: Tree):Int{
    tree.run {
        return leaf
    }
}

fun method(tree: Tree):Unit{
    tree.run {
        grow()
    }
}

class Tree{

    val leaf = 2

    fun grow():Unit{
      println("this tree growing")
    }
}

2、apply

The apple extension function is a scope function. Calling the apply function of an object can call any method of the object within the scope and return the object. The apply and run functions are very similar, the difference is that run returns a value, while apply returns an object

fun main() {
    ArrayList<Int>().apply {
        this.add(1)
        this.add(2)
        this.add(3)
    }.run {
        for (i in this) {
            println(i)
        }
    }
}

3、let

The let extension function is a scope function. When you need to define a variable in a specific scope, you can use it

let, in addition, let has another function is to judge the property as null .

fun main() {

  val a = 3

    //作用域
    a.let {
        val b = a+2
        println(b)
    }

     //判null
    val c:String? = null
    c?.let {
        println(c.length)
    }
}

Six: Case: Extend the findViewById method for Activity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        R.id.btn_test.onClick(this){
            println("click btn_test")
        }

    }


}

 private fun Int.onClick(activity: Activity, function: () -> Unit) {
          activity.findViewById<View>(this).setOnClickListener {
              function() 
          }
}

Seven: Case: Four operations

//四则运算
fun main() {
    while (true) {
        println("=============请输入你的表达式=============")
        val input = readLine()
        try {
            input?.let {
                val ret = calculate(input)
                println("{$input}={$ret}")
                println("=============是否继续使用(y/n)=============")
                val cmd = readLine()
                cmd?.let {
                    if (cmd == "n")
                        exitProcess(0)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}




fun calculate(input: String): String {
    val add = "+"
    val sub = "-"
    val mul = "*"
    val eli = "/"

    if (input.contains(add)) {
        val nums = input.trim().split(add)
        return operate(nums[0].toDouble(), nums[1].toDouble(), add).toString()
    } else if (input.contains(sub)) {
        val nums = input.trim().split(sub)
        return operate(nums[0].toDouble(), nums[1].toDouble(), sub).toString()
    } else if (input.contains(eli)) {
        val nums = input.trim().split(eli)
        return operate(nums[0].toDouble(), nums[1].toDouble(), eli).toString()
    } else if (input.contains(mul)) {
        val nums = input.trim().split(mul)
        return operate(nums[0].toDouble(), nums[1].toDouble(), mul).toString()
    }
    return "计算有误"
}

fun operate(s: Double, s1: Double, s2: String): Double {
   return when (s2) {
        "+" -> s + s1
        "-" -> s - s1
        "/" -> s / s1
        "*" -> s * s1
       else -> {0.0}
   }

}

Guess you like

Origin blog.csdn.net/qq_34123324/article/details/131158333