Kotlin扩展函数(also apply run let)和with函数

发布于:2024-07-03 ⋅ 阅读:(93) ⋅ 点赞:(0)

also apply run let with的使用例子


    private fun testOperator() {
        /**
         * also
         */
        val person = Person("ZhangSan", 18)
        person.also {
            // 通常仅仅打印使用, 也可以通过it修改
            it.name = "ZhangSan1"
            println("also inner name: " + it.name)
        }
        println("also name: ${person.name}")
        /**
         * apply
         */
        person.apply {
            // 因为this的缘故, 访问成员变量更容易, 不需要使用"it."或者"this."
            increaseAge()
            name = "WangWu"
            println("apply inner age: $age")
        }
        println("apply name: ${person.name}")
        /**
         * run
         */
        val person1 = Person("HeHe", 18)
        val person2 = person1.run {
            // run和let都会返回最后一个元素
            println("run inner name: $name")
            Person("Hello", 18)
        }
        println("run name: ${person1.name}")
        println("run name: ${person2.name}")
        /**
         * let
         * run可以完全替代let和with, let可以对空情况的统一处理
         */
        var person3: Person? = Person("LiSi", 18)
        val flag = Random.nextInt(10)
        if (flag > 0) {
            person3 = null
        }
        person3.let {
            if (it == null) return@let
            it?.name = "LiSi1"
            println("let inner person3: $person3")
        }
        println("let person3: $person3")

        /**
         * with
         * with不是扩展函数, 属于标准库函数
         */
        val person4: Person = Person("MaLiu", 18)
        val result = with(person4) {
            age = 24
            println("with inner age: $age")
            480
        }
        println("with result: $result")
    }

    class Person(var name: String, var age: Int) {
        fun increaseAge() {
            age += 1
        }

        fun changeName() {
            name = "YongLe"
        }
    }

扩展函数和with函数的特点概括

图片