Parentheses in anonymous functions

It is not clear to me if/when/why there need to be parentheses in anonymous functions.

Let’s consider:

val numLetters = “Mississippi”.count({ letter →
letter == ‘s’
})
println(numLetters) //no parentheses, prints 4

However, parentheses need to be in:

println({
val currentYear = 2019
“Welcome to SimVillage, Mayor! (copyright $currentYear)”
}())

Without those parentheses, nothing will print. Both use a function (count() and println()) and both functions take a function argument as their parameter.

Why does one require () and the other does not?

You can leave out the parens only when passing an lambda function as the last parameter. println takes a String. In the bottom case you’re declaring a function and then call it so you turn it into a String and then pass the String. You’re not passing the lambda function so you can’t leave out the parens.

Those aren’t anonymous functions, they are lambda expressions. An anonymous function starts with fun().

In your first example you are defining a lambda and passing it to the count() function. The count() function will execute the lambda you pass to it.

In your second example you are defining a lambda and then invoking it yourself with the parentheses.

1 Like