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
相关推荐
Haha_bj1 天前
七、Kotlin——扩展(Extensions)
android·kotlin
urkay-1 天前
Android getDrawingCache 过时废弃
android·java·开发语言·kotlin·iphone·androidx
用户69371750013841 天前
24.Kotlin 继承:调用超类实现 (super)
android·后端·kotlin
alexhilton1 天前
借助RemoteCompose开发动态化页面
android·kotlin·android jetpack
QING6182 天前
Jetpack Compose Brush API 简单使用实战 —— 新手指南
android·kotlin·android jetpack
QING6182 天前
Jetpack Compose Brush API 详解 —— 新手指南
android·kotlin·android jetpack
鹿里噜哩2 天前
Spring Authorization Server 打造认证中心(二)自定义数据库表
spring boot·后端·kotlin
用户69371750013842 天前
23.Kotlin 继承:继承的细节:覆盖方法与属性
android·后端·kotlin
Haha_bj2 天前
五、Kotlin——条件控制、循环控制
android·kotlin