What if your code's math is secretly wrong because you ignored operator precedence?
Why Operator precedence in Kotlin? - Purpose & Use Cases
Imagine you are solving a math problem by hand, mixing addition, multiplication, and subtraction without clear rules. You write down the operations in the order they appear, hoping the answer is right.
This manual way is slow and confusing. You might add before multiplying or subtract before adding, leading to wrong answers. It's easy to make mistakes and hard to check your work.
Operator precedence gives clear rules about which operations to do first. It's like having a priority list so your calculations always follow the same order, making your code correct and easier to understand.
val result = 2 + 3 * 4 - 5 // What is the result?
val result = 2 + (3 * 4) - 5 // Multiplication happens before addition and subtraction
With operator precedence, you can write complex expressions confidently, knowing they will be evaluated correctly every time.
When calculating a shopping bill with discounts and taxes, operator precedence ensures you apply multiplication for tax before adding the discount, so the final price is accurate.
Manual calculation order can cause errors.
Operator precedence sets clear rules for operation order.
This makes code reliable and easier to read.