java - Java有惰性求值吗?

标签 java lazy-evaluation

我知道 Java 在这种情况下具有智能/惰性评估:

public boolean isTrue() {
    boolean a = false;
    boolean b = true;
    return b || (a && b); // (a && b) is not evaluated since b is true
}

但是呢:

public boolean isTrue() {
    boolean a = isATrue();
    boolean b = isBTrue();
    return b || a;
}

即使 isBTrue() 返回 true,是否也会调用 isATrue()

最佳答案

嗯,就语言而言 - 是的,这两个函数都被调用了。

如果你把函数改写成这样:

public boolean isTrue() {
    return isBTrue() || isATrue();
}

如果第一个函数为真,则不会调用第二个函数。


但这是短路评估,而不是惰性评估。惰性评估用例如下所示:

public interface LazyBoolean {
    boolean eval();
}

class CostlyComparison implements LazyBoolean {
  private int a, b;

  public CostlyComparison(int a, int b) { 
    this.a=a; 
    this.b=b; 
  }

  @Override 
  public boolean eval() {
    //lots of probably not-always-necessary computation here
    return a > b;
  }
} 

public LazyBoolean isATrue() {
  return new CostlyComparison(10,30);  //just an example
}

public boolean isTrue() {        // so now we only pay for creation of 2 objects
    LazyBoolean a = isATrue();   // but the computation is not performed; 
    LazyBoolean b = isBTrue();   // instead, it's encapsulated in a LazyBoolean
    return b.eval() || a.eval(); // and will be evaluated on demand;
                                 // this is the definition of lazy eval.
}

关于java - Java有惰性求值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15189209/

相关文章:

javascript - 表达式的 Angular 惰性一次性绑定(bind)

java - 在JAVA中读取和打印CSV文件

java - spring mongoTemplate 查找专栏

java - JUnit 4.12 : testing util classes

haskell - 惰性和多态值

clojure延迟函数执行

java - 在 Java 中进行销售后减少 MySQL 数据库中的库存数量

java - Excel 中显示的 Apache POI : getting a number as a string,

properties - 惰性的 Kotlin 委托(delegate)属性是线程本地的

javascript - 如何在 JavaScript 中交换二维数组中的两个元素? (对我从 Chrome 中的 console.log 看到的内容感到困惑)