Functional Programming With Java 简明教程

Eager vs Lazy Evaluation

热切求值意味着一遇到表达式就对其求值,而延迟求值是指在需要时对表达式求值。请参阅以下示例来了解该概念。

import java.util.function.Supplier;

public class FunctionTester {
   public static void main(String[] args) {
      String queryString = "password=test";
      System.out.println(checkInEagerWay(hasName(queryString)
         , hasPassword(queryString)));
      System.out.println(checkInLazyWay(() -> hasName(queryString)
         , () -> hasPassword(queryString)));
   }

   private static boolean hasName(String queryString){
      System.out.println("Checking name: ");
      return queryString.contains("name");
   }

   private static boolean hasPassword(String queryString){
      System.out.println("Checking password: ");
      return queryString.contains("password");
   }

   private static String checkInEagerWay(boolean result1, boolean result2){
      return (result1 && result2) ? "all conditions passed": "failed.";
   }

   private static String checkInLazyWay(Supplier<Boolean> result1, Supplier<Boolean> result2){
      return (result1.get() && result2.get()) ? "all conditions passed": "failed.";
   }
}

Output

Checking name:
Checking password:
failed.
Checking name:
failed.

在 checkInEagerWay() 函数中,首先会评估参数然后执行其语句。而 checkInLazyWay() 先执行其语句,然后按需评估参数。因为 && 是一个短路运算符,所以 checkInLazyWay 只会评估为 false 的第一个参数,而根本不会评估第二个参数。