The Solution: Anonymous Function Syntax

A lambda expression is a “function literal”. The other syntax for function literals is the anonymous function:

  val squarifier = fun(x: Int): Int { return x * x }

  println(squarifier.invoke(3))

Here, squarifier has the same algorithm as before, just written in the form of an anonymous function. Here, we have to state our return type explicitly, just as we do for a regular function.

Syntactically, an anonymous function is a function declaration without the function name. We assign the anonymous function to a property, pass it as a parameter, etc., just as we would do for a lambda expression. And we execute the function the same way as we would do for a lambda expression, such as calling invoke() on it.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.