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