Just as we define string literals, hello, or double literals (12.34), we can also define function literals. A function literal is a function that is defined inline. To do this, 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()
You will notice in this example that once a function literal is defined, we can invoke it later using parentheses, just as 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...