急切评估与懒惰评估


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

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.";
   }
}

输出

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

这里 checkInEagerWay() 函数首先评估参数,然后执行其语句。而 checkInLazyWay() 执行其语句并根据需要评估参数。由于 && 是一个短路运算符,因此 checkInLazyWay 只评估第一个参数,该参数为 false,根本不评估第二个参数。