我知道 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/