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