January 2017
Intermediate to advanced
420 pages
9h 25m
English
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) ...Read now
Unlock full access