美文网首页
13. let{},run{},apply{},also{},w

13. let{},run{},apply{},also{},w

作者: 努力生活的西鱼 | 来源:发表于2021-10-22 14:13 被阅读0次
1. let
public inline fun <T, R> T.let(block: (T) -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return block(this)
}

把当前调用对象,作为参数传入block()代码块中。

代码示例:

fun testLet():Unit {
    "HIG".let {
        println(it); // HIG
        it.reversed();
    }.let {
        println(it) // GIH
    }
}
1. run()函数

源码:

public inline fun <T, R> T.run(block: T.() -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return block()
}
1.1 run{}用法
  • run{}里面的高阶函数,是运行在当前作用域内,这个代码块是独立的
  • 可以在里面写一点与项目无关的代码,因为它不会影响项目的运行
private fun testRun1():Unit {
    val str = "Java";

    kotlin.run {
        val str = "Kotlin"; // 和上面的变量不会冲突
        println("str is $str");
    }

    println("str is $str");
}

输出:
str is Kotlin
str is Java
1.2 a.run{}
private fun testRun2() {
    val str :String = "Kotlin";
    str.run {
        println("length is ${this.length}");
        println("first is ${this.first()}");
        println("last is ${this.last()}");
    }
}

在其中我们可以使用this关键字,因为在这里它就是代码str对象,可以省略

2. apply函数
public inline fun <T> T.apply(block: T.() -> Unit): T {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    block()
    return this
}

先是调用了block函数,然后返回当前的调用者对象this,意思就是执行完block()代码块逻辑后,再次返回当前的调用者对象。

测试代码:
private fun testApply(): Unit {
    val list = mutableListOf<String>();
    list.add("A");
    list.add("B");
    list.add("C");
    println("list = $list");

    val a = ArrayList<String>();
    a.apply {
        add("D");
        add("E");
        add("F");
        println("a = $a");
    }
}

output:
list = [A, B, C]
a = [D, E, F]
1. also{}
源码:

public inline fun <T> T.also(block: (T) -> Unit): T {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    block(this)
    return this
}
1. with{}
源码:
public inline fun <T, R> with(receiver: T, block: T.() -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return receiver.block()
}
  • with()函数传入了一个接收者对象receiver,然后使用该对象receiver去调用传入的lambda代码块。
测试代码:
private fun testWithFun():Unit {
    val list = mutableListOf<String>();
    list.add("A");
    list.add("B");
    list.add("C");
    println("常规写法: list = $list");

    with(list){
        add("D");
        add("E");
        add("F");
        println("with函数写法: $list");
    }
}

相关文章

网友评论

      本文标题:13. let{},run{},apply{},also{},w

      本文链接:https://www.haomeiwen.com/subject/dgncaltx.html