Kotlin学习之----内置函数apply、let、run、with、also的使用

目录

总结:

一、apply 用法: info.apply{}

二、run用法 : info.run{}

三、let用法:info.let{}

四、with用法 : with(info)

五、also:info.also{} //返回info本身



总结:

apply、let、run、with是kotlin里面常见的内置函数

apply 里面可以使用this,返回this

run里面可以使用this,返回自定义

let 里面不可以使用this,返回自定义

with和run使用场景一样,只不过和run的调用方式不一样

also里面可以使用it,返回调用对象本身。

一、apply 用法: info.apply{}

1、apply函数返回类型,返回info本身(this)

2、apply函数的匿名函数里面持有的this == info,就是info本身(因为T.()的原因)

data class ApplyTest(var name : String , var age : Int)
fun main(){
    var name : String? ;
    name = "lidongxu" ;
    var applyTest = ApplyTest("menshen" , 34)
    applyTest.apply {
        println("Apply CodeBlock LetTest1 name = {$name} , age = {$age}")
        this.age = 100
        println("Apply CodeBlock LetTest2 name = {$name} , age = {$age}")
    }
    println("applyTest name = {${applyTest.name} , age = {${applyTest.age}")
    //给StringBuilder扩展一个apply函数
    fun StringBuilder.myApply(block: StringBuilder.() ->Unit) : StringBuilder {
        block()
        return this
    }
    
    var sb = StringBuilder("123")
    sb.myApply {
        append("456")
        append("654")
    }
    println(sb)
}
/**
 * 打印结果
 *  Apply CodeBlock LetTest1 name = {macoli} , age = {34}
 *  Apply CodeBlock LetTest2 name = {macoli} , age = {100}
 *  applyTest name = {menshen , age = {100}
 *  123456654
 */

二、run用法 : info.run{}

1、run函数返回类型,根据最后一行而定

2、run函数的匿名函数里面持有的this == info,就是info本身(因为T.()的原因)

//除了返回值不一样,其余和上面例子一样的

三、let用法:info.let{}

1、let函数返回类型,根据最后一行而定

2、let函数内it相当于info

//使用let做空判断
fun main(){
    println(judgeMethod("麦克LI"))
}

fun judgeMethod(value : String?) : String {
    return value?.let {
        "欢迎光临 , $it"
    } ?: "啥都没有进来干啥"
}

四、with用法 : with(info)

with和run一样,只不是调用方式不一样,with相当于是全局函数

fun main(){
    var test = "李东旭"
    var v1 = with(test , ::getStrLen)
    var v2 = with(v1 , ::getStrLenStr)
    println(v2)//输出"test长度是 $value"
}

fun getStrLen(value : String) = value.length
fun getStrLenStr(value : Int) = "test长度是 $value"

五、also:info.also{} //返回info本身

fun main(){
    alsoTest()
}
fun alsoTest() {
    var r = "ILoveChina".also {
        println("ALSO CODE BLOCK $it")
        println("ALSO CODE BLOCK ${it.toUpperCase()}")
        it.forEach {
            print("CHAR $it , ")
        }
        println()
    }
    println("OUTOF ALSO CODE BLOCK $r" )
}

猜你喜欢

转载自blog.csdn.net/mldxs/article/details/127134124