kotlin expansion function (apply, let, run)

1. The apply
apply function can be regarded as a configuration function, passing in an object and returning a configured object. Any method of the object can be directly called within the scope:

 class Student{
    
    
        var name:String?=null
        var age:Int?=null
    }
    fun main(){
    
    
        class Student{
    
    
            var name:String?=null
            var age:Int?=null
        }
        fun main(args: Array<String>) {
    
    
            val studentInfo= Student().apply {
    
    
                name="小明"
                age=20
            }
            print(studentInfo)
        }
    }

Function: Simplify object initialization

2、let

The let function applies a variable to a lambda expression and lets the it keyword refer to it.

```java
   fun main() {
    
    
    val restlt= listOf(6,7,8,9).get(3).let {
    
    
        it*it
    }
    print(restlt)
}
输出:81```

The difference between let and apply:
①. let will pass the receiver to lambda, apply will pass nothing
②. After the anonymous function is executed, apply will return the current receiver, and let will return the last line of lambda

3、run

fun main() {
    
    
    val str="午饭吃什么"
    val result=str.run {
    
    
        contains("吃")
    }
    print(result)
}
输出:true

run function execution function reference:

fun main() {
    
    
    "my name is jack"
        .run(::isLong)
        .run(::show)
        .run(::println)
}
fun isLong(name:String)=name.length>=10

fun show(isLong: Boolean):String{
    
    
    return if (isLong){
    
    
        "name is jd"
    }else{
    
    
        "please create new name"
    }
}

Comparison between run and apply:
only looking at the scope, run is similar to apply, but ran does not return the receiver. It returns the lanbda result, true or false, and other types can also be returned.

Guess you like

Origin blog.csdn.net/qq_26554909/article/details/130790324