difference between "&&" and "and" in kotlin
Asked Answered
V

2

16

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?

Vue answered 1/8, 2023 at 2:49 Comment(0)
C
26

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.")
}
Commemorative answered 1/8, 2023 at 2:57 Comment(3)
I'm not very familiar with Kotlin, but I'm wondering why it's implemented as an intrinsic instead of as a function that simply returns a && b.Medical
@Medical Because it's actually a bitwise AND operator, see here for more information: en.wikipedia.org/wiki/Bitwise_operationProvitamin
@TiebeGroosman To clarify: It's a bitwise operation when applied to the Int type, and a logical operation when applied to the Bool type. kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/and.html kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/and.htmlCommemorative
S
-1

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

Smell answered 6/8, 2023 at 17:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.