androidkotlinlogical-operatorslogical-and

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?


Solution

  • 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.")
    }