Braces vs brackets in functions


What’s the difference between these 2 forEachIndexed?

  1. forEachIndexed()
    Is it possible to take some examples and help me understand the difference please?


They are the same function, but the syntax for the first (and only) argument is different. The documentation of Sequence shows that there is only 1 function:

forEachIndexed expects a function as a parameter, so if you have a function from somewhere, you can simply pass it:

// Note: This is a lambda, but the function could have been defined in another way.
val anExistingFunction: (Int, Long) -> Unit = { index, item -> println("At $index: $item") }

If you inline the value above, you are allowed to drop the parentheses as forEachIndexed accepts a function as the final argument:

someSequence.forEachIndexed { index, item -> println("At $index: $item") }

You can move the lambda to the right of the parentheses with any function of which the last parameter is a function type. If there is only 1 parameter, you can also drop the parentheses.