Functional Programming With Java 简明教程

Functional Programming with Java - Closure

闭包是一种函数,它与其周围状态一同组成一段函数。闭包函数通常有权访问外部函数的作用域。在下面给出的示例中,我们创建了一个函数 getWeekDay(String[] days),它返回一个函数,可以返回一个工作日的文本等价物。此处 getWeekDay() 是返回一个围绕调用函数的作用域的函数的闭包。

以下示例展示了闭包的工作原理。

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

Sunday