Kotlin的折痕是什么允许我将运算函数放在右括号后面? [英] What is it about Kotlin's fold that allows me to put the operation function after the closing parentheses?
本文介绍了Kotlin的折痕是什么允许我将运算函数放在右括号后面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Kotlin中有关Iterable.fold(...)
的事情是什么,允许我将operation
函数放在后的右括号内?
What is it about Iterable.fold(...)
in Kotlin that allows me to put the operation
function after the closing parentheses?
val numbers = listOf(5, 2, 10, 4)
// operation function passed as the second param of fold
val sumDoubled1 = numbers.fold(0, { sum, n -> sum + n * 2 })
println(sumDoubled1)
// operation function after the closing paren of fold
val sumDoubled2 = numbers.fold(0) { sum, n -> sum + n * 2 }
println(sumDoubled2)
推荐答案
It is called Passing trailing lambdas means, if a methods takes last parameter input as function(aka method literal) then it can be placed outside that method call though you can also place it inside the brackets as well. A simple example would be:
fun main() {
processInput("Lambda", { println(it) })
processInput("Passing trailing lambda") { println(it) }
processInput("Passing trailing lambda with named param") { input -> println(input) }
}
fun processInput(input:String, method:(str:String)->Unit){
method(input.toUpperCase()) // additional logic
}
输出:
LAMBDA
PASSING TRAILING LAMBDA
PASSING TRAILING LAMBDA WITH NAMED PARAM
这篇关于Kotlin的折痕是什么允许我将运算函数放在右括号后面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文