Enriching is Easy

Today I’d like to talk about a pattern that as far as I know is unique to Java 8. It makes use of the unusual way Java 8 implements lambdas as single-method interfaces, and the support for default methods in interfaces, to produce what I call “enriched lambdas”.

Here’s a simple example: a “Logged function” that logs every call that is made to it:

Now we can add the logging behaviour to any function by assigning or casting it to LoggedFunction rather than Function:

How does this work? LoggedFunction has only one method without a default implementation, so any lambda that matches the signature of this method can be cast to an instance of LoggedFunction. Instead of overriding the “apply” method of LoggedFunction, the lambda will override the “applyLogged” method, which the default “apply” method implementation delegates to.

Octarine uses this pattern in a variety of ways, notably to build up Schemas, Serialisers and Deserialisers from single lambda expressions:

In this case, the unimplemented method is used to configure the object, and all other methods (with their default implementations) use this method to obtain their configuration.

This pattern is similar in some respects to the “enrich my library” pattern in Scala, which uses implicits – it provides a safe and convenient way to “upcast” simple lambdas to objects with enriched behaviour.

%d bloggers like this: