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

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

For example:

class Person(var name: String, var age: Int) {
    fun eat() {
        println("吃饭")
    }

    fun work(hour: Int): Int {
        println("$name $age 工作 $hour,赚${hour * 60}")
        return hour * 60
    }
}

fun main(args: Array<String>) {
    var s: String? = null

    //没用let前,每个都要加 ? 判断是否为空
    val len = s?.length
    var ss = s?.toByte()

    println(len)
    println(ss)

    //使用let后,只需加一次?判空
    s?.let {
        val len = it.length
        it.toByte()
    }



    val person = Person("zhang", 18)

    /**
     * with()把传入的对象作为接受者,函数内可使用this指代该对象来访问公有属性和方法。
     * 函数的返回值为函数块最后一行或指定的return表达式。
     */
    val result1 = with(person) {
        age = 19
        eat()
        work(996)
    }
    println("结果1:$result1")
    println("----------")


    /**
     * run()是with()和let()的结合,它可以像with()一样在函数体中使用this指代该对象,也可以像let()一样为对象做判空。
     */
    val result2 = person?.run() {
        age = 20
        work(996)
        eat()
    }
    println("结果2:$result2")
    println("----------")


    /**
     * apply()和run()相似,不同的是,run()返回最后一行代码的值,而apply()返回传入的对象本身。
     */
    val result3 = person?.apply {
        age = 21
        eat()
        work(996) // 返回person对象
    }
    println("结果3:$result3")
    println("----------")

    /**
     * also()和apply()相似,不同的是,also()在函数体内用it指代该对象,而apply()在函数体中用this指代该对象。
     */
    val result4 = person?.also {
        it.age = 22
        it.eat()
        it.work(996) // 返回传入的person对象
    }
    println("结果4:$result4")
    println("----------")
}

output:

null
null
eat
Zhang 19 work 996, earn 59760
result 1: 59760
----------
zhang 20 work 996, earn 59760
eat
result 2: kotlin.Unit
----------
eat
Zhang 21 Work 996, earn 59760
Result 3: Person@7530d0a
----------
Eat
Zhang 22 Work 996, earn 59760
Result 4: Person@7530d0a
----------

Kotlin common expressions let,?:, as?,?.,!!_zhangphil's blog-CSDN blog it.todo() //Use it in the function instead of the object object to access properties and methods. it.todo() //The let function will only be executed if the object is not null. When a is not null, execute the statement in the braces (it must not be null) if a == null, then it is null. = null, then ab() is null if a is not b. If a is b, then a as b. When a is null, nothing is executed. If a==null, throw a null pointer. =null, execute a. When a==null, execute b. https://blog.csdn.net/zhangphil/article/details/129264159

Guess you like

Origin blog.csdn.net/zhangphil/article/details/129327285