Kotlin学习6.2:Lambda的特性
(一)如果函数的最后一个参数接受函数,那么传入的 Lambda 表达式可以放在圆括号之外:
fun calculate(a: Int, b: Int, cal: (Int, Int) -> Int) {
print("a + b = ${cal(a, b)}")
}
fun main(args: Array<String>) {
calculate(1, 1) { a, b -> a + b }
}
(二)如果 Lambda 表达式只有一个参数,并且编译器自己可以识别出签名,也可以不用声明唯一的参数并忽略->, 该参数会隐式声明为it:
fun calculate(a: Int, cal: (Int) -> Int) {
print(cal(a))
}
fun main(args: Array<String>) {
calculate(2) { it * it }
}
(三)如果 Lambda 表达式没有参数,也可以忽略->, 并且不会隐式声明参数it,可参考下一点的例子。
(四)如果 Lambda 表达式是调用时唯一的参数,那么圆括号也可以省略:
fun myPrint(p: () -> Unit) {
p()
}
fun main(args: Array<String>) {
myPrint {
print("timestamp is ${System.currentTimeMillis()}")
}
}
(五)Lambda 表达式将隐式返回最后一个表达式的值,但可以使用限定的返回语法,即通过标签显式返回一个值:
fun calculate(a: Int, cal: (Int) -> Int) {
print(cal(a))
}
fun main(args: Array<String>) {
calculate(2) {
it * it
}
calculate(2) {
return@calculate it * it
}
}
(六)从 Kotlin1.1 起,如果 Lambda 表达式的参数未使用,则可以用下划线代替其名称:
fun calculate(a: Int, b: Int, cal: (Int, Int) -> Int) {
print(cal(a, b))
}
fun main(args: Array<String>) {
calculate(1, 2) { _, b ->
println("a 参数未使用")
b * b
}
}
(七)从 Kotlin1.1 起,Lambda 表达式参数支持解构声明语法,我们通过 Kotlin 内置的forEach()方法遍历map来测试:
fun main(args: Array<String>) {
val map = mapOf(1 to 1, 2 to 2, 3 to 3)
map.forEach {
println("${it.key} to ${it.value}")
}
// 显示声明it参数的类型
map.forEach { entry: Map.Entry<Int, Int> ->
println("${entry.key} to ${entry.value}")
}
// 将Map.Entry类型的it参数解构
map.forEach { (k, v) ->
println("$k to $v")
}
}