Kotlin的内置函数 apply、let、run、with、also

let

1.let函数返回类型,是根据匿名函数的最后一行变化而变化
2.let函数中的匿名函数里面持有的是it == 集合自身

java 复制代码
fun main() {
    var num1 = 1
    var num2 = 1
    var result:Int
    result = num1 + num2
    var str = result?.let {//传入本身,it指代本身即result,result不为空则执行let,为空则不执行
         println("传进来的值为${it}")
        "${num1} + ${num2} = ${result}" //此处为返回的值
    }?:"传进来的值为null"
    print(str)
}

传进来的值为2

1 + 1 = 2

apply

apply: info:apply

1.apply函数返回类型,都是info自身
2.apply函数中的匿名函数里面持有的是this == info自身

run

run:str.run

1.run函数返回类型,是根据匿名函数最后一行变化而变化
2.run函数中的匿名函数里面持有的是this == str自身

java 复制代码
fun runFunction(){
    val str = "yuknight"
    val r = str.run {
        //this == str
        true
    }
    println(r)
    //run中匿名函数
    val strRun = str.run {
        str.length > 5
    }
        .run {
            if (this) "字符串合格" else "字符串不合格"
        }
        .run {
            "[$this]"
        }
    println(strRun)
    //run中使用具名函数
    val strRun1 = str.run(::isLong)
        .run(::showText)//::表示引用函数
        .run(::mapText)
    println(strRun1)
}

fun isLong(str: Stri

true

字符串合格

字符串合格

with

with with(str)
1.with函数返回类型,是根据匿名函数最后一行变化而变化
2.with函数中的匿名函数里面持有的是this == str自身.
3.跟run在使用的时候不一样

java 复制代码
fun isLong(str: String) = str.length > 5
fun showText(isLong: Boolean) = if (isLong) "字符串合格" else "字符串不合格"
fun mapText(getShow: String) = "[$getShow]"
fun getStrLen(str: String) = str.length
fun getLenInfo(len: Int) = "字符长度:$len"
fun getInfoMap(info: String) = "[$info]"
fun getshow(content: String) = println(content)

fun withMethod() {
    val str = "yuknight"
    val length = with(str) {
        this.length//this == str  //返回类型为匿名函数里面最后一行
    }
    println(length)
    val r1 = wi

与run不同的是width需要传入参数

also

also str.also

1.also函数返回类型,都是str自身
2.also函数中的匿名函数里面持有的是it == str自身.

java 复制代码
fun alsoMethod() {
    val str = "YuKnight"
    str.also {
        it.length  //it == str
        println("$it") //返回值为str自身
    }
    //str.also特点,可以链式调用
    str.also {
        println("str原始数据是:$it")
    }.also {
        println("str转换成小写:${it.toLowerCase()}")
    }.also {
        println("链式调用结算 ${it}")
    }
}

YuKnight

str原始数据是:YuKnight

str转换成小写:yuknight

链式调用结算 YuKnight

总结

方法 返回值 自身指代 是否传参
let 最后一行 it
apply 自身 this
run 最后一行 this
with 最后一行 this
also 自身 it
相关推荐
铉铉这波能秀2 小时前
如何在Android Studio中使用Gemini进行AI Coding
android·java·人工智能·ai·kotlin·app·android studio
爱学啊1 天前
3.Android Compose 基础系列:在 Kotlin 中创建和使用函数
kotlin·compose·android compose开发基础
低调小一1 天前
LRU缓存科普与实现(Kotlin 与 Swift)
开发语言·缓存·kotlin
雨白1 天前
深入理解协程的运作机制 —— 调度、挂起与性能
android·kotlin
xqlily1 天前
Kotlin:现代编程语言的革新者
android·开发语言·kotlin
消失的旧时光-19431 天前
人脸跟随 ( Channel 实现(缓存5条数据 + 2度过滤 + 平滑移动))
android·java·开发语言·kotlin
消失的旧时光-19432 天前
Android回退按钮处理方法总结
android·开发语言·kotlin
VIjolie2 天前
协程CoroutineContext理解
kotlin
alexhilton3 天前
突破速度障碍:非阻塞启动画面如何将Android 应用启动时间缩短90%
android·kotlin·android jetpack