First example - Mississippi count - parentheses


as we learn with the second example:

fun main(args: Array) { println({ val currentYear = 2018 “Welcome to SimVillage, Mayor! (copyright $currentYear)” }()) }

, anonymous functions will only work when it has been called using parentheses.

In the first example :

val numLetters = “Mississippi”.count({ letter -> letter == ‘s’ }) print(numLetters) // Prints 4

, these parentheses are missing but it is still working. I can’t understand the systematology here. Is the compiler lenient in this case?
Please help me to understand this.

Best regards

1 Like

I had the same question…I wish someone would clear it up

Because the count function calls that anonymous function internally whereas in the next example println requires a string there which is what your anonymous function returns when it is called.

See pg. 75 for an example of a function that takes a function. Note that it is calling the passed in anonymous function.

Straight from the Shorthand Syntax subsection of the Defining a Function that Accepts a Function section:

“When a function accepts a function type for its last parameter, you can also omit the parentheses around the lambda argument.”