Vincent Tsen
Android Kotlin Weekly

Android Kotlin Weekly

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!

Vincent Tsen's photo
Vincent Tsen
·Aug 6, 2022·

2 min read

What is Trailing Lambda and Comma in Kotlin?

Subscribe to my newsletter and never miss my upcoming articles

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)

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)

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)
}

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
}

Without Trailing Comma

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

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.

Did you find this article valuable?

Support Vincent Tsen by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this