Kotlin之let,apply,run,with等函数区别2

Kotlin之let,apply,run,with等函数区别2


以前也总结过Kotlin的一些内置函数let,apply,run,with的区别——地址,后面又增加了also,takeIf,takeUnless等函数,所以这里重新总结下,然后介绍下使用场景。

前提介绍

Kotlin和Groovy等语言一样,支持闭包(block),如果函数中最后一个参数为闭包,那么最后一个参可以不写在括号中,而写在括号后面,如果只有一个参数,括号也可以去掉。

如下所示

fun toast() {
    button.setOnClickListener({
       Toast.makeText(context, "test", Toast.LENGTH_SHORT).show()
    })
}

fun toast() {
    button.setOnClickListener {
        Toast.makeText(context, "test", Toast.LENGTH_SHORT).show()
    }
}

后面介绍的几个函数都是这样的,这样就很容理解。

repeat

repeat函数是一个单独的函数,定义如下。

/**
 * Executes the given function [action] specified number of [times].
 *
 * A zero-based index of current iteration is passed as a parameter to [action].
 */
@kotlin.internal.InlineOnly
public inline fun repeat(times: Int, action: (Int) -> Unit) {
    contract { callsInPlace(action) }

    for (index in 0..times - 1) {
        action(index)
    }
}

通过代码很容易理解,就是循环执行多少次block中内容。

fun main(args: Array<String>) {
    repeat(3) {
        println("Hello world")
    }
}

运行结果

Hello world
Hello world
Hello world

with

with函数也是一个单独的函数,并不是Kotlin中的extension,指定的T作为闭包的receiver,使用参数中闭包的返回结果

/**
 * Calls the specified function [block] with the given [receiver] as its receiver and returns its result.
 */
@kotlin.internal.InlineOnly
public inline fun <T, R> with(receiver: T, block: T.() -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return receiver.block()
}

代码示例:

fun testWith() {
    // fun <T, R> with(receiver: T, f: T.() -> R): R = receiver.f()
    with(ArrayList<String>()) {
        add("testWith")
        add("testWith")
        add("testWith")
        println("this = " + this)
    }.let { println(it) }
}
// 运行结果
// this = [testWith, testWith, testWith]
// kotlin.Unit

class文件

 public static final void testWith()
  {
    Object localObject = new ArrayList();
    ArrayList localArrayList1 = (ArrayList)localObject;
    int $i$a$1$with;
    ArrayList $receiver;
    $receiver.add("testWith");
    $receiver.add("testWith");
    $receiver.add("testWith");
    String str = "this = " + $receiver;
    System.out.println(str);
    localObject = Unit.INSTANCE;
    Unit it = (Unit)localObject;
    int $i$a$2$let;
    System.out.println(it);
  }

let

首先let()的定义是这样的,默认当前这个对象作为闭包的it参数,返回值是函数里面最后一行,或者指定return

fun <T, R> T.let
  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Kotlin中的let是一个拓展函数,它可以更优雅地处理可空变量问题。当我们使用let函数时,它会将调用它的对象作为参数传递给lambda表达式,并且在lambda表达式中可以对该对象进行操作。这样可以避免对可空变量进行null检查,提高代码的可读性和简洁性。同时,let函数还可以在链式调用中使用,使代码更加清晰。 具体来说,let函数有以下特点: 1. 它将调用它的对象作为lambda表达式的参数。 2. 在lambda表达式中可以对该对象进行操作。 3. let函数的返回值是lambda表达式的返回值。 通过使用let函数,我们可以在处理可空变量时,避免使用繁琐的null检查,提高代码的可读性和简洁性。同时,let函数还可以与其他拓展函数一起使用,例如applyrun等,以便更灵活地处理对象。 总结来说,Kotlin中的let函数是一个非常实用的拓展函数,可以更优雅地处理可空变量问题,并且在链式调用中提高代码的可读性和简洁性。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [十三、Kotlin进阶学习:内联函数let、also、with、runapply的用法。](https://blog.csdn.net/weixin_43936741/article/details/125996295)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [Kotlin要点之一 | let](https://blog.csdn.net/jxq1994/article/details/103007338)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值