Skip to main content
Donovan LaDuke - Developer

Boolean Infix Functions and Short Circuiting

Featured in Android Weekly Issue 606

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 at one of the services below, it goes a long way in helping run this site. Thank you in advance!

Donate with PayPal Buy me a Coffee on Ko-fi Support me on Patreon