kotlin高阶函数

高阶函数 run, with, apply, also, let, takeIf, takeUnless, repeat

高阶函数 T.() -> R 和 (T) -> R

在泛型中经常会出现T.() -> R(T) -> R类型的回调函数, 他们的区别在于: T.() -> R

可以在回调函数中使用this来指代回调函数的传参T, 而(T) -> R使用的是 it来指代.

具体调用如下

T.()

(T) it

(T) this

run 执行回调函数并返回执行结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@kotlin.internal.InlineOnly
public inline fun <R> run(block: () -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block()
}

@kotlin.internal.InlineOnly
public inline fun <T, R> T.run(block: T.() -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block()
}

with 传入对象并返回对象指定函数的执行结果

1
2
3
4
5
6
7
@kotlin.internal.InlineOnly
public inline fun <T, R> with(receiver: T, block: T.() -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return receiver.block()
}

apply 执行回调函数并返回对象自身

1
2
3
4
5
6
7
8
@kotlin.internal.InlineOnly
public inline fun <T> T.apply(block: T.() -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block()
return this
}

also 将自身对象传入回调函数执行并返回自身对象

1
2
3
4
5
6
7
8
9
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.also(block: (T) -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block(this)
return this
}

let 将自身对象传入回调函数执行并返回执行结果

1
2
3
4
5
6
7
@kotlin.internal.InlineOnly
public inline fun <T, R> T.let(block: (T) -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block(this)
}

takeIf 如果将自身对象执行断言方法, 如果断言为真返回自身否则返回 null

1
2
3
4
5
6
7
8
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.takeIf(predicate: (T) -> Boolean): T? {
contract {
callsInPlace(predicate, InvocationKind.EXACTLY_ONCE)
}
return if (predicate(this)) this else null
}

takeUnless 如果将自身对象执行断言方法, 如果断言为假返回自身否则返回 null

1
2
3
4
5
6
7
8
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.takeUnless(predicate: (T) -> Boolean): T? {
contract {
callsInPlace(predicate, InvocationKind.EXACTLY_ONCE)
}
return if (!predicate(this)) this else null
}

repeat 执行指定次数的回调函数

1
2
3
4
5
6
7
8
@kotlin.internal.InlineOnly
public inline fun repeat(times: Int, action: (Int) -> Unit) {
contract { callsInPlace(action) }

for (index in 0 until times) {
action(index)
}
}

kotlin高阶函数
https://wttch96.github.io/post/java/kotlin/kotlin高阶函数.html
作者
Wttch
发布于
2022年3月31日
许可协议