Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between "&&" and "and" in kotlin

What's the difference between "&&" and "and" in kotlin?

in my code, when first condition is false, i've noticed that the condition after "and" is still evaluated but not evaluated in "&&" case. why is that?

like image 270
AT Amrani Avatar asked Dec 14 '25 04:12

AT Amrani


1 Answers

You answered the question yourself - if you use and then you evaluate the entire expression.

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/and.html

In answer to the question as to why it happens, it is because and is not an operator, but an infix function on the Bool type. Short-circuiting is a compiler rule that applies to boolean operators, not to function calls.

So why is this and function useful? There may be some cases where invoking the right expression has side effects, and you want these side effects to happen regardless of the left expression.

if (!(saveToDatabase() and writeToNoficationQueue())) {
     print("At least one thing went wrong there. Check the logs to find out.")
}
like image 179
Andrew Shepherd Avatar answered Dec 16 '25 21:12

Andrew Shepherd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!