Kotlin's let, with, run, also and apply

1、let

In the scope of let, it can be used to refer to the called object by default, and it can also be named by yourself. There is a return value, the return value is the last line or specify a return expression

val count = "hello".let { 
                it.plus("1")
                print("${it.length}")
                it.length    //返回值
            }

custom naming

val count = "hello".let { strHello ->
                strHello.plus("1")
                print("${strHello.length}")
                strHello.length
            }

2、with

With (parameter passing) scope can use this to refer to the passed object, using its properties and methods. There is a return value, the return value is the last line

val hello = "hello"
        val world = "world"
        val pair = Pair(hello, world)
        val numWorld = with(pair){
            val lengthHello = this.first.length
            second.length    //返回值
        }

3、run

Use this in the run scope to refer to the caller object. There is a return value, the return value is the last line

val hello = "hello"
        val world = "world"
        val pair = Pair(hello, world)
        val strWorld = pair.run {
            val lengthHello = this.first.length
            val lengthWorld = second.length
            second  //返回值
        }

4、also

Use it in the also scope to refer to the caller. There is a return value, and the return value is the caller itself.

val hello = "hello"
        val world = "world"
        val pair = Pair(hello, world)
        val strReceive: Pair<String, String> = pair.also {
            val lengthHello = it.first.length
            val lengthWorld = it.second.length
        }
        strReceive.first.showToast()

Because the return value of also is the object itself, the above code can also be modified to be a chain call.

val hello = "hello"
        val world = "world"
        val pair = Pair(hello, world)
        pair.also {
            val lengthHello = it.first.length
            val lengthWorld = it.second.length
        }.first.showToast()

5、apply

Use this to refer to the object in the apply scope. There is a return value, and the return value is the object itself.

//数据类
data class Person(
        var name: String = "",
        var age: Int = 0
    )
val modifyPerson = Person().apply {
            name = "aaa"
            age = 10
        }
        modifyPerson.name.showToast()   //此时name="aaa"

 

 

Guess you like

Origin blog.csdn.net/nsacer/article/details/123249383