5 ways to implement Closures in Java 8

5 ways to implement Closures in Java 8

Closures are nothing but stateful functions! A few definitions from the web include:

  • A closure is a combination of a function bundled together (enclosed) with references to its surrounding state
  • A closure gives you access to an outer function?s scope from an inner function

Uses of Closures include data privacy, partial application & currying.

Image for post

My limited exposure to Closures and Java 8 has yielded me 5 possible ways through which you can implement closures in Java 8. Some of these examples may not be accepted as closures by the vast majority of readers, but I still have them here to demonstrate how closures can be perceived from a conceptual perspective.

Having an idea about functional interfaces, anonymous inner classes & lambda expressions will help you understand this story better.

Example 1: Using custom Functional Interface & inner class

Image for post

Highly debatable, but textOfWeekday can be considered a closure because it bundles the convert function and the weeks data (private to textOfWeekday) without deliberately defining weeks within the convert function.

Example 2: Using custom Functional Interface & Lambda expression

Image for postThis example uses the Functional Interface declared in Example 1

This is similar to Example 1, but differs in the way the functional interface is implemented: Lambda expression instead of inner class.

Example 3: Using predefined Functional Interface & Lambda expression

Image for post

This is similar to Example 2, except that the use of predefined ?Function? interface avoids the need to write a custom interface. It is in fact, an anti-pattern to write custom functional interfaces for those that Java has predefined.

Example 4: Using predefined Functional Interface, Lambda expression & inner function having access to the parent scope

Image for post

This stands out from the previous two examples in a way that it returns an inner function (in the form of a lambda expression) that encloses/remembers weeks data which is in the scope of the parent function (getTextOfWeekday).

Unlike example 1, this example does not require any classes (inner) to bundle the data with the returned function.

Example 5: Using predefined Functional Interface, Lambda expression & inner function having access to parent scope which is nothing but state passed by the client

Image for post

Unlike Example 4, weeks is not defined in the parent (getTextOfWeekday) scope but obtained as a parameter from the client/caller.


Note that Java 8 covers/encloses states by values and not by variables, unlike few other languages. The above are some of the possibilities through which I have tried to explain the concept of stateful functions.

Try out the examples yourself by downloading the source code (GitHub).

Feel free to comment/correct as I always capitalize on my mistakes to learn!


No Responses

Write a response