What is Trailing Lambda and Comma in Kotlin?

August 27, 2022


Trailing lambda and trailing comma are the 2 important Kotlin features that you must know if you’re new to Kotlin!

This article was originally published at vtsen.hashnode.dev on Aug 6, 2022.

Trailing lambda is something new in Kotlin that other programming language doesn’t have. At least, I do not aware of any other programming language that supports it.

When you see code like this:

var result = operateOnNumbers(a, b) { input1, input2 ->
    input1 + input2
}
println(result)
Enter fullscreen modeExit fullscreen mode

It basically means operateOnNumbers() has 3 parameters. The last parameter is a function definition, which you usually either pass in the function reference or lambda.

var result = operateOnNumbers(
    input1 = a,
    input2 = b,
    operation = { input1, input2 ->
        input1 + input2
    }
)
println(result)
Enter fullscreen modeExit fullscreen mode

Somehow I am still not getting used to this trailing lambda syntax. It looks like a function implementation.

So my mind always needs to automatically map to this (the code outside the parentheses is actually the last parameter of the function) every time I see the Trailing Lambda syntax.

The signature and implementation of operateOnNumbers() looks like this:

fun operateOnNumbers(
    input1: Int,
    input2: Int,
    operation: (Int, Int) -> Int): Int {

    return operation(input1, input2)
}
Enter fullscreen modeExit fullscreen mode

On the other hand, trailing commas is pretty common in other language.

** With Trailing Comma**

var result = operateOnNumbers(
    a, 
    b, // trailing comma here
) { input1, input2 ->
    input1 + input2
}
Enter fullscreen modeExit fullscreen mode

** Without Trailing Comma**

var result = operateOnNumbers(
    a, 
    b // no trailing comma here
) { input1, input2 ->
    input1 + input2
}
Enter fullscreen modeExit fullscreen mode

The benefit of using it is allowing easier diff and merge. For me, it makes my copy and paste life easier. Yupe, I do a lot of copy & paste!



Conclusion

I hope you enjoy this short post. I want to blog about this (especially Trailing Lambda) because it sometimes looks confusing to me, especially the function call is a bit complex. I always need to remind myself, the code outside the parentheses is actually the last parameter of the function.



See Also



Source link

Comments 0

Leave a Reply

Your email address will not be published. Required fields are marked *