美文网首页
Kotlin中let, with, run, apply, al

Kotlin中let, with, run, apply, al

作者: kermitye | 来源:发表于2021-02-24 21:04 被阅读0次

    Kotlin中let, with, run, apply, also方法的使用总结

    调用方式 传递参数(it/this) 返回值
    let 链式调用 it 计算结果
    with 函数调用 this 计算结果
    run 链式调用 this 计算结果
    apply 链式调用 this 调用对象本身
    also 链式调用 it 调用对象本身

    链式调用及函数调用的区别

    //链式调用
    xx.let {
    }
    //函数调用
    with(xx) {
    }
    

    总结:这个就不做详细说明了

    传递参数it与this的区别

    var person: Person? = null
    var info = ""
    person = Person("张三", 18)
    info = person?.let{
        it.name = "xxx"
        it.age = 26
        "${it.name} 年龄为 ${it.age}"
    }
    
    info = person?.run {
        name = "xxx"
        age = 28
        "$name 年龄为 $age"
    }
    
    

    总结:当函数内需要多次引用调用对象,或者调用其方法或对其参数赋值时可以选择使用run,而如果只是引用一下调用对象,或直接调用对象本身,比如我只需要打印上述person的内容,那么直接使用let就可以了

    返回值为计算结果与调用对象本身的区别

    val person = Person("张三", 18)
    val info: String = person.run {
        name = "李四"
        age = 28
        "$name 年龄为 $age"
        //this
    }
    println(info)
    
    val person1 = person.apply {
        name = "李四"
        age = 28
        "$name 年龄为 $age"
        //apply的效果也相当于是run方法的返回值为this
    }
    
    

    总结:如上代码所示,方法体内都是同样的代码,但是一个返回的是最后的结果也就是String,而一个返回的是对象的本身,也就是Person对象。不同的是run可以返回任意想要的数据类型,而apply只能返回调用对象本身而已。

    相关文章

      网友评论

          本文标题:Kotlin中let, with, run, apply, al

          本文链接:https://www.haomeiwen.com/subject/tdlefltx.html