Whats the difference using and omitting parens for functions


#1

A bit of confusion with parens and lambdas. What is the logic when to omit or use parens.

val squares = IntArray(5) { it+3 }

Now to check if 3 is in the array. Why does the third example fail to compile?

  1. Paren around any()
    squares.any(){it == 3}

  2. No Paren around any()
    squares.any({it == 3})

  3. Fails when I also add paren around any()
    squares.any()({it == 3})


#2

If the last argument of the function is a lambda, it can be written outside the parenthesis. That’s why your third example does not compile. Actually there is a 4th option that allows a smoother syntax, that is when the only argument of a function is a lambda you can omit parenthesis at all:

squares.any { it == 3 }

Those syntactic sugars are made for readability when creating a DSL. Have a look at a Gradle build file written in Kotlin, it is awesome thanks to that!