Trailing lambda is one thing new in Kotlin that different programming language would not have. No less than, I don’t conscious of some other programming language that helps it.
While you see code like this:
var outcome = operateOnNumbers(a, b) { input1, input2 ->
input1 + input2
}
println(outcome)
It means operateOnNumbers()
has 3 parameters. The final parameter is a perform definition, which you often both go within the perform reference or lambda.
var outcome = operateOnNumbers(
input1 = a,
input2 = b,
operation = { input1, input2 ->
input1 + input2
}
)
println(outcome)
In some way I’m nonetheless not getting used to this trailing lambda syntax. It appears like a perform implementation.
So my thoughts at all times must mechanically map to this (the code outdoors the parentheses is the final parameter of the perform) each time I see the Trailing Lambda syntax.
The signature and implementation of operateOnNumbers()
appears like this:
enjoyable operateOnNumbers(
input1: Int,
input2: Int,
operation: (Int, Int) -> Int): Int {
return operation(input1, input2)
}
Then again, trailing commas is fairly widespread in different languages.
With Trailing Comma
var outcome = operateOnNumbers(
a,
b,
) { input1, input2 ->
input1 + input2
}
With out Trailing Comma
var outcome = operateOnNumbers(
a,
b
) { input1, input2 ->
input1 + input2
}
The advantage of utilizing it’s permitting simpler diff and merge. For me, it makes my copy-and-paste life simpler. Yupe, I do lots of copy & paste!
Conclusion
I hope you get pleasure from this brief publish. I need to weblog about this (particularly Trailing Lambda) as a result of it generally appears complicated to me. The perform name is a bit advanced. I at all times have to remind myself, the code outdoors the parentheses is the final parameter of the perform.