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

本文详细介绍了Kotlin中的let, apply, run, with等函数的区别和使用场景,包括它们的语法特性、返回值以及在实际编程中的应用示例。此外,还提到了also, takeIf和takeUnless等辅助函数,帮助理解如何在Kotlin中优雅地处理对象和条件判断。" 132995359,20014461,全球领先的语音识别技术公司,"['人工智能', '语音识别']
摘要由CSDN通过智能技术生成

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值