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
相关推荐
tangweiguo0305198721 小时前
Kable使用指南:Android BLE开发的现代化解决方案
android·kotlin
yzpyzp1 天前
kotlin的函数前面增加suspend关键字的作用
android·开发语言·kotlin
jiet_h1 天前
Android Kotlin ObjectAnimator 和 ValueAnimator 全面解析
android·开发语言·kotlin
Android技术之家1 天前
Kotlin与Compose:Android开发的现代化变革
android·java·开发语言·kotlin
小孔龙1 天前
01.Kotlin Serialization - 基础用法
kotlin·json
叽哥1 天前
Kotlin学习第 5 课:Kotlin 面向对象编程:类、对象与继承
android·java·kotlin
叽哥1 天前
Kotlin学习第 6 课:Kotlin 集合框架:操作数据的核心工具
android·java·kotlin
前行的小黑炭1 天前
Android LayoutInflater 是什么?XML到View的过程
android·java·kotlin
前行的小黑炭2 天前
Android :如何提升代码的扩展性,方便复制到其他项目不会粘合太多逻辑,增强你的实战经验。
android·java·kotlin
珠峰下的沙砾2 天前
在kotlin中如何使用像java中的static
kotlin