Boolean Infix Functions and Short Circuiting
The two ways to perform boolean operations in Kotlin are the operators &&
and ||
or using the infix functions and
and or
. They are mostly the same, but there is one key difference. The operators perform short circuiting but the infix functions do not.
Short Circuiting is an optimization where the right hand boolean operands is not evaluated if the result is known from the left operand (e.g. the left hand operand is true
for ||
or false
for &&
). For a better visual, see the example below.
fun isTrue() { println("Eval True"); return true }
fun isFalse() { println("Eval False"); return false }
val result = isTrue() || isFalse
// prints
// Eval True
val result2 = isTrue() or isFalse()
// prints
// Eval True
// Eval False
Neither of these two approaches are right or wrong, but it is important to know the difference. The best takeaway is that boolean expressions should have no side-effects, that way the operators and infix functions are functionally the same. Until next time, thanks!
Did you find this content helpful?
Please share this post and be sure to subscribe to the RSS feed to be notified of all future articles!
Want to go above and beyond? Help me out by sending me $1 on Ko-fi. It goes a long way in helping run this site and keeping it advertisement free. Thank you in advance!