计算&&和||

Computing && and ||

我在 Scala 中有一个值定义为

val x = SomeClassInstance()
val someBooleanValue = x.precomputedValue || functionReturningBoolean(x)

functionReturningBoolean 运行时间长,为了避免重新计算 functionReturningBoolean(x),我将其存储在 x.precomputedValue.

我的问题是:如果 x.precomputedValuetrue,是否会计算 functionReturningBoolean(x)

更普遍:一旦编译器在 "OR" 语句中看到 true 的值,它是否会查看语句中的第二个条件? 同样,在 "AND" 语句中,例如 a && b,如果 afalse,是否会查看 b

My question is: if x.precomputedValue is true, will functionReturningBoolean(x) ever be computed?

没有。 &&|| 在 Scala 短路。你可以从 the documentation:

看出

This method uses 'short-circuit' evaluation and behaves as if it was declared as def ||(x: => Boolean): Boolean. If a evaluates to true, true is returned without evaluating b.


More Generally: as soon as the compiler sees a value of true in an "OR" statement, will it even look at the second condition in the statement? Similarly, in an "AND" statement, such as a && b, will b ever be looked at if a is false?

是的。 Scala 中的所有表达式都必须是静态类型良好的,无论它们是否会在运行时执行。