Kotlin之精选

1 如何巧用Kotlin内置函数?

1.1 let、also、with、run、和apply区别?

Kotlin之精选_第1张图片

1.2 使用示例区别?

1.2.1 let

private fun higherFunCompare() {
        val people : People = People("chen", 1, listOf("x", "y"))

        /**
         * let
         * 作用:1.避免写判空的处理;2.使用it替代object对象在其作用域内访问属性&方法;3.返回值是最后一行 == return ...
         */
        val let = people?.let {
            it.age
            it.name
            it.isYong()
            it.isMen()
            999
        }
        LogUtils.d(TAG, "people?.let:$let")
        // people?.let:999

        // java
        if (people != null) {
            people.age
            people.name
            people.isYong()
            people.isMen()
            999
        }
    }

1.2.2 also

private fun higherFunCompare() {
        /**
         * also:类似let函数,但区别在于返回值:
         * 3.返回值是传入的对象的本身
         */
        val also = people?.also {
            it.age
            it.name
            it.isYong()
            it.isMen()
            999
        }
        LogUtils.d(TAG, "people?.also:$also")
        // people?.also:com.read.kotlinlib.model.People@1f24758d
    }

1.2.3 with

private fun higherFunCompare() {
        /**
         * with:
         * 1.调用同一个对象的多个方法/属性时,省去重复的对象名,直接调用方法名/属性即可;2.返回值是最后一行
         */
        val with = with(people) {
            LogUtils.d(TAG,"my name is $name, I am $age years old, ${isYong()}, ${isMen()}")
            999
        }
        LogUtils.d(TAG, "with(people):$with")
        // my name is chen, I am 1 years old, false, true
        // with(people):999

        // java
        LogUtils.d(TAG,"my name is $people.name, I am $people.age years old, ${people.isYong()}, ${people.isMen()}")
    }

1.2.4 run

private fun higherFunCompare() {        
        /**
         * run:结合了let、with两个函数的作用
         * 作用:1.避免写判空的处理;2.使用it替代object对象在其作用域内访问属性&方法;3.返回值是最后一行;
         *      4.调用同一个对象的多个方法/属性时,省去重复的对象名,直接调用方法名/属性即可
         */
        val run = people?.run {
            LogUtils.d(TAG,"my name is $name, I am $age years old, ${isYong()}, ${isMen()}")
            999
        }
        LogUtils.d(TAG, "people?.run:$run")
        // my name is chen, I am 1 years old, false, true
        // people?.run:999
    }

1.2.5 apply

private fun higherFunCompare() {
        /**
         * apply:与run函数类似,但区别在于返回值:
         * 3.返回值是传入的对象的本身;
         */
        val apply = people?.apply {
            LogUtils.d(TAG,"my name is $name, I am $age years old, ${isYong()}, ${isMen()}")
            999
        }
        LogUtils.d(TAG, "people?.apply:$apply")
        // my name is chen, I am 1 years old, false, true
        // people?.apply:com.read.kotlinlib.model.People@1f24758d
    }

3 参考链接

如何巧用Kotlin内置函数?

你可能感兴趣的:(Kotlin)