Boolean Infix Functions and Short Circuiting
source link: https://dladukedev.com/articles/028_boolean_infix_ops/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Boolean Infix Functions and Short CircuitingSkip to main content
Boolean Infix Functions and Short Circuiting
January 18, 2024
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!
© Donovan J. LaDuke - 2024 | All Rights Reserved
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK