Android kotlin中let also apply run with的区别

 

使用测试代码

class ExtendTest {


    @Test
    fun letDemo() {
        val user = UserInfo()
        val result = user.let {
            it.name = "name1"
            it.age = 20
            it.show()
            80
        }
        println("result=$result")
//        输出结果
//        name=name1 and age=20
//        result=80
    }


    @Test
    fun applyDemo() {
        val user = UserInfo()
        val result = user.apply {
            name = "name1"
            age = 20
            show()
            80
        }
        println("result=$result")
//        输出结果
//        name=name1 and age=20
//        result=User对象
    }


    @Test
    fun alsoDemo() {
        val user = UserInfo()
        val result = user.also {
            it.name = "name1"
            it.age = 20
            it.show()
            80
        }
        println("result=$result")

//        输出结果
//        name=name1 and age=20
//        result=User对象
    }


    @Test
    fun runDemo() {
        val user = UserInfo()
        val result = user.run {
            name = "name1"
            age = 20
            this.show()
            80
        }
        println("result=$result")
//        输出结果
//        name=name1 and age=20
//        result=80
    }

    @Test
    fun withDemo() {
        val user = UserInfo()
        val result = with(user) {
            name = "name1"
            age = 20
            this.show()
            80
        }
        println("result=$result")
//        输出结果
//        name=name1 and age=20
//        result=80
    }


    class UserInfo {
        var name = ""
        var age = 30
        fun show() {
            println("name=$name and age=$age")
        }
    }
}

  

let的源码

@kotlin.internal.InlineOnly
public inline fun <T, R> T.lets(block: (T) -> R): R {
    contract {//它将表明 block 这个扩展方法一定会在这里被执行一次
        //callsInPlace(lambda: Function<R>, kind: InvocationKind = InvocationKind.UNKNOWN)
        //lambda:执行代码块
        //kind:上面 block 将会被执行的次数,kind 有四种类型
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return block(this)
}

public enum class InvocationKind {
    AT_MOST_ONCE,//最多执行一次
    AT_LEAST_ONCE,//至少执行一次
    EXACTLY_ONCE,//有且只有一次
    UNKNOWN//未知  默认值
}

  

  

contract关键字

  contract(契约)是一种 Kotlin 面向编译器约定的一种规则,它帮助编译器更加智能地识别某些需要特定的代码条件,为代码创建更加友好的上下文关联环境。

  参考地址:https://blog.csdn.net/HJXASLZYY/article/details/122676634  感谢大佬

 

posted @ 2022-05-13 14:59  bg_不够  阅读(52)  评论(0编辑  收藏  举报