13.1. Presentation

Decorators are similar in syntax and purpose to Java annotations. However, the concepts behind them are very different. Indeed, whereas Java annotations are compiler or VM directives, decorators are actually plain functions, more precisely higher order functions.

Note

Higher order functions (HOF) are functions that process functions, i.e. that take a function as parameter, and may return a new function.

A decorator is thus a function that take the function to decorate as parameter, and return a new function, generally a wrapper that do some stuffs before or after calling the original function.

The name can remind the well known GoF pattern, with good reason. This pattern describe a design that allow an object to be augmented by wrapping it in an other object with the same interface, delegating operations to the wrapped object. This is exactly what a decorator does here, the interface being "function" (more precisely a java.lang.invoke.MethodHandle).