就像这个表达:
fun main() = runBlocking { ... }
我们是否执行
runBlocking
函数并将 { }
主体作为函数参数传递?
这叫什么?
我知道它会立即执行 main 因为括号。
这不是单一语言功能。
首先,您可以使用单个表达式作为函数体,以替换该函数的返回值。这称为单表达式函数。例如,以下
f
的声明是等效的:
fun f(): Int {
return 0
}
fun f() = 0
其次,当函数采用函数类型作为最后一个参数时,您可以在调用的
)
之后将 lambda 表达式传递给该参数:
fun iTakeAFunction(x: Int, f: () -> Unit) { }
// the following are equivalent
iTakeAFunction(0, { println("Hello World") })
iTakeAFunction(0) { println("Hello World") }
此语法称为 trailing lambda。
当 lambda 表达式是您传递的 only 参数时,您甚至可以省略
()
:
fun iTakeAFunction(f: () -> Unit) { }
// the following are equivalent
iTakeAFunction({ println("Hello World") })
iTakeAFunction() { println("Hello World") }
iTakeAFunction { println("Hello World") }
runBlocking
是这样的函数,因此问题中的代码脱糖为:
fun main(): Unit {
return runBlocking({ ... })
}
换句话说,
main
只是以 lambda 表达式作为参数来调用 runBlocking
。
请注意,您通常不会在
return
返回函数中看到像上面那样的 Unit
,因为您 c