A function literal as an "anonymous function", i.e. a function that is not declared, but passed immediately as an expression. Consider the following example:
Function max is a higher-order function, i.e. is takes a function value as the second argument. This second argument is an expression that is itself a function, i.e. a function literal. As a function, it is equivalent to
For a function to accept another function as a parameter, we have to specify a function type for that parameter. For example the abovementioned function max is defined as follows:
The parameter less is of type (T, T) -> Boolean, i.e. a function that takes two parameters of type T and returns a Boolean: true if the first one is smaller than the second one.
In the body, line 4, less is used as a function: it is called by passing two arguments of type T.
A function type is written as above, or may have named parameters, for documentation purposes and to enable calls with named arguments.
The full syntactic form of function literals, i.e. literals of function types, is as follows:
- A function literal is always surrounded by curly braces,
- parameter declarations in the full syntactic form go inside parentheses and have optional type annotations,
- the optional return type annotation goes after the parameter list,
- the body goes after an '->' sign.
If we leave all the optional annotations out, what's left looks like this:
As this is the most common case, Kotlin allows us to leave the parentheses out as well, if no type annotations are present, and so we get the short syntactic form for functional literals:
It very common that a function literal has only one parameter. If Kotlin can figure the signature out itself, it allows us not to declare the only parameter, and will implicitly declare it for us under the name it:
Note that if a function takes another function as the last parameter, the function literal argument can be passed outside the parenthesized argument list. See Higher-order functions and the grammar for callSuffix.
See the grammar for function literals here.
Besides ordinary functions, Kotlin supports extension functions. This kind of functions in so useful, that extension function literals are also supported. One of the most important examples of their usage is Type-safe Groovy-style builders.
An extension function differs from an ordinary one in that it has a receiver type specification. One can specify a receiver type in a function literal as well:
Receiver type may be specified only in the full syntactic form of a function literal (remember that parameter types and return type annotations are optional in this form).
Such a literal has a function type with receiver:
it can be called with a dot or in infix form (since it has only one parameter):
See This expressions.