English 中文(简体)
Closure
  • 时间:2024-09-17

Functional Programming with Java - Closure


Previous Page Next Page  

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 calpng function s scope.

Following example shows how Closure works.

import java.util.function.Function;

pubpc class FunctionTester {
   pubpc 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));      
   }

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

Output

Sunday
Advertisements