-
常见高阶函数
public inline fun <T> Array<out T>.forEach(action: (T) -> Unit): Unit {
for (element in this) action(element)
}
forEach 内部也是 for 实现
自定义高阶函数
fun main() {
computeTimeOfExecution {
for (i in 0..1000) {
println(i)
}
}
}
//计算函数调用时间
fun computeTimeOfExecution(block: () -> Unit) {
val start = System.currentTimeMillis()
block()
val end = System.currentTimeMillis() - start
println("耗时=$end ms")
}
- 调用高阶函数只有一个参数时,可以省略括号
带参数
fun main() {
computeTimeOfExecution("haha") {
for (i in 0..1000) {
println(i)
}
}
}
//计算函数调用时间
fun computeTimeOfExecution(name: String, block: () -> Unit) {
val start = System.currentTimeMillis()
block()
val end = System.currentTimeMillis() - start
println("$name 耗时=$end ms")
}
- 调用高阶函数有多个参数时,括号不能省略
内联函数
使用高阶函数会带来一些运行时的效率损失,但是在许多情况下通过内联化 lambda 表达式可以消除这类的开销.
内联后实际
可以反编译对比
使用内联
public static final void main() {
int $i$f$computeTimeOfExecution = false;
long start$iv = System.currentTimeMillis();
int var3 = false;
int i = 0;
boolean var6;
for(short var5 = 1000; i <= var5; ++i) {
var6 = false;
System.out.println(i);
}
long end$iv = System.currentTimeMillis() - start$iv;
String var9 = "耗时=" + end$iv + " ms";
var6 = false;
System.out.println(var9);
}
不使用内联
public static final void main() {
computeTimeOfExecution((Function0)null.INSTANCE);
}
内联高阶函数 return
val arrayOf = arrayOf(1, 2, 3, 4)
arrayOf.forEach {
if (it==2)return@forEach//相当于continue
println("$it")
}
输出
1
3
4