Does Java have lazy evaluation?

后端 未结 9 1589
面向向阳花
面向向阳花 2020-12-03 16:44

I know that Java has smart/lazy evaluation in this case:

public boolean isTrue() {
    boolean a = false;
    boolean b = true;
    return b || (a &&         


        
9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-03 17:33

    SE8 (JDK1.8) has introduced Lambda expressions, which can make lazy evaluations more transparent. Consider the statement in the main method of the following code:

    @FunctionalInterface
    public interface Lazy {
       T value();
    }
    
    class Test {
       private String veryLongMethod() {
          //Very long computation
          return "";
       }
    
       public static  T coalesce(T primary, Lazy secondary) {
          return primary != null? primary : secondary.value();
       }
    
       public static void main(String[] argv) {
          String result = coalesce(argv[0], ()->veryLongMethod());
       }
    }
    

    The called function coalesce returns the first given non-null value (as in SQL). The second parameter in its call is a Lambda expression. The method veryLongMethod() will be called only when argv[0] == null. The only payload in this case is inserting ()-> before the value to be lazily evaluated on demand.

提交回复
热议问题