DEV Community

Cover image for What is Trailing Lambda and Comma in Kotlin?
Vincent Tsen
Vincent Tsen

Posted on • Updated on • Originally published at vtsen.hashnode.dev

What is Trailing Lambda and Comma in Kotlin?

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

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 mode Exit fullscreen mode

It 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 mode Exit 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 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 mode Exit fullscreen mode

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

With Trailing Comma

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

Without Trailing Comma

var result = operateOnNumbers(
    a, 
    b // no trailing comma here
) { input1, input2 ->
    input1 + input2
}
Enter fullscreen mode Exit 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. The function call is a bit complex. I always need to remind myself, the code outside the parentheses is the last parameter of the function.


Originally published at https://vtsen.hashnode.dev.

Top comments (2)

Collapse
 
steve1rm profile image
Steve

I think not having the trailing comma is more readable. My IDE highlights this as a problem. useless trailing comma

Collapse
 
vtsen profile image
Vincent Tsen

Not that bad for me. Having said that, most of my code doesn't have the trailing comma. No complaints from my IDE.