Lambdas and Higher-Order Functions
Trailing Lambda
Move the final lambda argument outside the parentheses.
Trailing Lambda
TrailingLambda.kt
fun buildSteps(count: Int, label: (Int) -> String): String {
var text = ""
for (index in 1..count) {
if (text != "") {
text += ","
}
text += label(index)
}
return text
}
fun main() {
val count =
val steps = buildSteps(count) { index ->
"step$index"
}
println("count=$count")
println("steps=$steps")
}
fun buildSteps(count: Int, label: (Int) -> String): String {
var text = ""
for (index in 1..count) {
if (text != "") {
text += ","
}
text += label(index)
}
return text
}
fun main() {
val count =
val steps = buildSteps(count) { index ->
"step$index"
}
println("count=$count")
println("steps=$steps")
}
fun buildSteps(count: Int, label: (Int) -> String): String {
var text = ""
for (index in 1..count) {
if (text != "") {
text += ","
}
text += label(index)
}
return text
}
fun main() {
val count =
val steps = buildSteps(count) { index ->
"step$index"
}
println("count=$count")
println("steps=$steps")
}
trailing-lambda
When a lambda is the last argument, Kotlin can place it after the call.