Why does AND and OR infix functions from kotlin-stdlib don't short-circuit as && and ||?

97 Views Asked by At

I've noticed that both and and or kotlin-stdlib's infix functions have this javadoc:

Performs a logical `and` operation between this Boolean and the [other] one. Unlike the `&&` operator, this function does not perform short-circuit evaluation. Both `this` and [other] will always be evaluated.

I'm curious about the reason behind it cause in my mind this was just a syntax-sugar for && and || but it turns out it's not

2

There are 2 best solutions below

0
Tenfour04 On BEST ANSWER

It's because there is sometimes a need for not short-circuiting. The whole point of these functions is to provide a way to logically combine Booleans without short circuiting.

It would be against the design principles of Kotlin to provide an alternate syntax for doing exactly the same thing, because this would make the language harder to read in general: no functionality benefit but more base knowledge required to be able to read code without looking up function or syntax documentation.

1
broot On

Adding to the answer by @Tenfour04, please note it would be technically tricky to short-circuit in this case. and() is a function and we can't call it without passing both arguments. Kotlin compiler would have to recognize this specific function and inline it with a custom bytecode to allow short-circuiting.