Function literals
Just like we define string literals, hello
, or double literals (12.34), we can also define function literals. To do so, we simply enclose the code in braces:
{ println("I am a function literal") }
Function literals can be assigned to a variable just like other literals:
val printHello = { println("hello") } printHello()
Notice in this example that once a function literal is defined, we can invoke it later using parentheses, like we do for a regular function. Of course, once defined, we can invoke the function multiple times.
Function literals can also accept parameters. For this, we write the parameters, along with types, before a thin arrow; this denotes the function body:
val printMessage = { message: String -> println(message) } printMessage("hello") printMessage("world")
As you can see, we pass in the parameter when invoking like a regular function. When a function literal is used in a place where the compiler...