Reputation: 73
I have a value in Scala defined as
val x = SomeClassInstance()
val someBooleanValue = x.precomputedValue || functionReturningBoolean(x)
functionReturningBoolean
has a long runtime and to avoid recomputing functionReturningBoolean(x)
, I am storing it in x.precomputedValue
.
My question is: if x.precomputedValue
is true
, will functionReturningBoolean(x)
ever be computed?
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
?
Upvotes: 1
Views: 145
Reputation:
My question is: if
x.precomputedValue
istrue
, willfunctionReturningBoolean(x)
ever be computed?
No. &&
and ||
in Scala short-circuit. You can tell from the documentation:
This method uses 'short-circuit' evaluation and behaves as if it was declared as
def ||(x: => Boolean): Boolean
. Ifa
evaluates totrue
,true
is returned without evaluatingb
.
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 asa && b
, willb
ever be looked at ifa
is false?
Yes. All expressions in Scala must be well-typed statically, whether they will be executed at runtime or not.
Upvotes: 4