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
相关推荐
zimoyin4 小时前
kotlin Android AccessibilityService 无障碍入门
android·开发语言·kotlin
_龙小鱼_19 小时前
Kotlin扩展简化Android动画开发
android·开发语言·kotlin
_龙小鱼_19 小时前
Kotlin 作用域函数(let、run、with、apply、also)对比
java·前端·kotlin
zhangphil1 天前
Android Coli 3 ImageView load two suit Bitmap thumb and formal,Kotlin(七)
android·kotlin
lpfasd1231 天前
Flutter与Kotlin Multiplatform(KMP)深度对比及鸿蒙生态适配解析
flutter·kotlin·harmonyos
androidwork2 天前
使用 Kotlin 和 Jetpack Compose 开发 Wear OS 应用的完整指南
android·kotlin
_龙小鱼_2 天前
Kotlin变量与数据类型详解
开发语言·微信·kotlin
androidwork3 天前
掌握 Kotlin Android 单元测试:MockK 框架深度实践指南
android·kotlin
圈圈编码3 天前
MVVM框架
android·学习·kotlin
橙子199110163 天前
在 Kotlin 中,什么是解构,如何使用?
android·开发语言·kotlin