Skip to main content

Command Palette

Search for a command to run...

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!

Updated
2 min read
What is Trailing Lambda and Comma in Kotlin?
V

I'm a self-taught hobbyist Android developer who loves to build projects and share valuable tips for new Android developers.

Feel free to comment, share or connect with me!

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 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 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 languages.

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. 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.

Kotlin Coding

Part 10 of 20

Learn the key concepts and best practices for programming in Kotlin from a self-taught Android developer.

Up next

Understand Fields and Properties in Kotlin

How Kotlin implicitly implements field, getter and setter function for you when you declare a property?