edenmark
edenmark

Reputation: 73

Computing && and ||

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

Answers (1)

user1804599
user1804599

Reputation:

My question is: if x.precomputedValue is true, will functionReturningBoolean(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. 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?

Yes. All expressions in Scala must be well-typed statically, whether they will be executed at runtime or not.

Upvotes: 4

Related Questions