美文网首页
with、run、apply、let、also 函数区别

with、run、apply、let、also 函数区别

作者: 戎码虫 | 来源:发表于2022-02-08 15:53 被阅读0次

    with 传参可以是任意对象,上下文为this,返回值为最后一行的结果

        val withResult = with(StringBuffer()) {
            println("start")
            append("hello")
            append(" ")
            append("world")
            println("end")
            toString()
        }
        println(withResult)
    

    run 任意对象调用,上下文为this,返回值为最后一行的结果

     val runResult = StringBuffer().run {
            println("start")
            append("hello")
            append(" ")
            append("world")
            println("end")
            toString()
        }
        println(runResult)
    

    apply 任意对象调用,上下文为this,返回值为对象本身

        val applyResult = StringBuffer().apply {
            println("start")
            append("hello")
            append(" ")
            append("world")
            println("end")
        }
        println(applyResult.toString())
    

    let 任意对象调用,上下文为it,返回值为最后一行结果

     val letResult = StringBuffer().let {
            println("start")
            it.append("hello")
            it.append(" ")
            it.append("world")
            println("end")
            it.toString()
        }
    
        println(letResult)
    

    以上不同写法运行结果一致:

    start
    end
    hello world
    

    also 任意对象调用,上下文为it,返回值为最后一行结果

         val alsoResult = StringBuffer().also {
            println("start")
            it.append("hello")
            it.append(" ")
            it.append("world")
            println("end")
        }
    
        println(alsoResult.toString())
    

    以上不同写法运行结果一致:

    start
    end
    hello world
    

    run、apply、let 、also都支持链式调用

    StringBuffer().run{  }.run{  }
    StringBuffer().apply{  }.apply{  }
    StringBuffer().let{  }.let{  }
    StringBuffer().also{  }.also{  }
    
    标准函数 调用方式 上下文 返回值
    with 任意对象参数传入 this 最后一行结果
    run 任意对象调用 this 最后一行结果
    apply 任意对象调用 this 对象本身
    let 任意对象调用 it 最后一行结果
    also 任意对象调用 it 对象本身

    相关文章

      网友评论

          本文标题:with、run、apply、let、also 函数区别

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