Aspects

Java 8 Onwards

Functional Programming

Streams

Useful Resources

Functional Programming - Closure



A closure is a function which is a combination of function along with its surrounding state. A closure function generally have access to outer function's scope. In the example given below, we have created a function getWeekDay(String[] days) which returns a function which can return the text equivalent of a weekday. Here getWeekDay() is a closure which is returning a function surrounding the calling function's scope.

Example - Usage of Closures

Following example shows how Closure works.

FunctionTester.java

package com.tutorialspoint;

import java.util.function.Function;

public class FunctionTester {
   public static void main(String[] args) {
      String[] weekDays = {"Monday", "Tuesday", "Wednesday", "Thursday",
         "Friday", "Saturday", "Sunday" };
      Function<Integer, String> getIndianWeekDay = getWeekDay(weekDays);
      System.out.println(getIndianWeekDay.apply(6));      
   }

   public static Function<Integer, String> getWeekDay(String[] weekDays){
      return index -> index >= 0 ? weekDays[index % 7] : null;
   }
}

Output

Run the FunctionTester and verify the output.

Sunday
Advertisements