Hi, I have a pretty basic question: What are the p...
# announcements
s
Hi, I have a pretty basic question: What are the practical uses/ advantages of Boolean functions like
and(), or(), not()
over Boolean operations like
&&, ||, !
. Thank you in advance for your answers.
e
Are there any? What prompted you to ask?
t
aren’t
and
and
or
not-shortcircuited? meaning both expressions will always be evaluated, with
&&
only the first one if false?
e
Are we talking about Kotlin here?
s
Just the option to use both. Yes they are not short-circuiting so the usecase would be if I would want to evaluate all parts of a statement regardless was the part results are?
t
Copy code
/**
     * 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.
     */
    public infix fun and(other: Boolean): Boolean
e
Yes. I would suggest to avoid using them in general code to avoid confusion. They are helpful, though, in some rare circumstance if you want to get a function references like
Boolean::add
to use with some higher-order function, albeit it is hard to come up with a practical example
add
and
or
are there mostly for completeness, to complement
xor
which is indeed useful sometimes.
s
Ah okay. Thank you!
j
it also can affect how you write for null safety:
Copy code
var foo: Boolean? = null
val bar = true
val result = foo?.and(bar) ?: false
var other = (foo ?: false) && bar
var yetAnother = foo == true && bar