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?
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?
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.")
}
The Operator: '&&'
The logical AND operator (&&) is used to compare the relationship between two Boolean expressions and will only return a true value if both expressions are true. Example:
var humid = true
var raining = true
var shorts = false
var sunny = false
// true AND true
println(humid && raining)
OUTPUT: true
// true AND false
println(humid && shorts)
OUTPUT: false
// false AND true
println(sunny && raining)
OUTPUT: false
// false AND false
println(shorts && sunny)
OUTPUT: false
The Operator: 'and'
The and function compares corresponding bits of two values. If both bits are 1, it is evaluated to 1. If either of the bits is 0, it is evaluated to 0. Example:
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bit Operation of 12 and 25
00001100 and
00011001
________
00001000 = 8 (In decimal)
Example: Bitwise and Operation
fun main(args: Array<String>) {
val number1 = 12
val number2 = 25
val result: Int
result = number1 and number2 // result = number1.and(number2)
println(result)
}
OUTPUT: 8
© 2022 - 2024 — McMap. All rights reserved.
a && b
. – Medical