0
0
Kotlinprogramming~15 mins

Operator precedence in Kotlin - Deep Dive

Choose your learning style9 modes available
Overview - Operator precedence
What is it?
Operator precedence is the set of rules that decide the order in which parts of a math or logic expression are calculated. It tells the computer which operations to do first when there are many in one line. Without these rules, expressions could be confusing and give different answers. Operator precedence helps make sure calculations happen in a clear and expected order.
Why it matters
Without operator precedence, computers would not know which part of an expression to calculate first, leading to wrong answers and bugs. Imagine trying to solve a math problem but not knowing if you should add or multiply first. Operator precedence solves this by giving a clear order, so your programs work correctly and predictably.
Where it fits
Before learning operator precedence, you should understand basic operators like +, -, *, /, and how expressions work in Kotlin. After mastering precedence, you can learn about associativity, operator overloading, and how to write complex expressions safely.
Mental Model
Core Idea
Operator precedence is the rulebook that tells which operation to do first when multiple operators appear in one expression.
Think of it like...
It's like following a recipe where some steps must happen before others, for example, you must bake the cake before frosting it.
Expression: 3 + 4 * 2

Precedence order:
  ┌───────────────┐
  │ Multiply (*)  │  ← highest priority
  ├───────────────┤
  │ Add (+)       │  ← lower priority
  └───────────────┘

Calculation flow:
3 + (4 * 2) = 3 + 8 = 11
Build-Up - 7 Steps
1
FoundationUnderstanding basic operators
🤔
Concept: Learn what operators like +, -, *, and / do in Kotlin.
In Kotlin, + adds numbers, - subtracts, * multiplies, and / divides. For example, 2 + 3 equals 5, and 6 / 2 equals 3. These operators let you do math in your programs.
Result
You can perform simple math calculations using these operators.
Knowing what each operator does is the first step to understanding how expressions are evaluated.
2
FoundationEvaluating simple expressions
🤔
Concept: Learn how Kotlin calculates expressions with one operator.
When you write 5 + 7, Kotlin adds 5 and 7 to get 12. If you write 10 - 4, Kotlin subtracts 4 from 10 to get 6. Each expression with a single operator is straightforward.
Result
Expressions with one operator produce expected results directly.
Simple expressions build the foundation for understanding more complex ones.
3
IntermediateMultiple operators in one expression
🤔Before reading on: do you think 3 + 4 * 2 equals 14 or 11? Commit to your answer.
Concept: When expressions have more than one operator, Kotlin uses precedence rules to decide the order of calculation.
In the expression 3 + 4 * 2, Kotlin does multiplication first because * has higher precedence than +. So it calculates 4 * 2 = 8, then adds 3 to get 11.
Result
3 + 4 * 2 evaluates to 11, not 14.
Understanding operator precedence prevents mistakes in multi-operator expressions.
4
IntermediateUsing parentheses to change order
🤔Before reading on: does (3 + 4) * 2 equal 14 or 11? Commit to your answer.
Concept: Parentheses override operator precedence by forcing the operations inside them to happen first.
In (3 + 4) * 2, Kotlin first adds 3 + 4 = 7 because of parentheses, then multiplies by 2 to get 14.
Result
(3 + 4) * 2 evaluates to 14.
Parentheses give you control over calculation order, which is essential for correct results.
5
IntermediateOperator precedence table overview
🤔
Concept: Learn the general precedence order of common Kotlin operators.
Kotlin operators have a hierarchy. For example: - Highest: unary operators like ++, -- - Then: *, /, % - Then: +, - - Then: comparison operators like >, < - Then: logical operators like &&, || This order tells Kotlin what to calculate first.
Result
You know which operators take priority in expressions.
Knowing the precedence table helps predict how complex expressions evaluate.
6
AdvancedAssociativity and same-precedence operators
🤔Before reading on: In 10 - 5 - 2, does Kotlin calculate (10 - 5) - 2 or 10 - (5 - 2)? Commit to your answer.
Concept: When operators have the same precedence, associativity rules decide the order of evaluation.
Most Kotlin operators like - and + are left-associative, so 10 - 5 - 2 is (10 - 5) - 2 = 3. Some operators, like assignment (=), are right-associative.
Result
10 - 5 - 2 evaluates to 3, not 7.
Understanding associativity avoids confusion when chaining same-precedence operators.
7
ExpertOperator precedence in custom operator overloading
🤔Before reading on: Can you change operator precedence by overloading operators in Kotlin? Commit to your answer.
Concept: Kotlin lets you define how operators work on your types but does not let you change their precedence or associativity.
When you overload operators like + or *, Kotlin uses the existing precedence rules. You cannot create new operators or change their priority. This keeps expressions consistent and predictable.
Result
Custom operators follow Kotlin's fixed precedence rules.
Knowing this prevents attempts to redefine precedence, which could cause confusing code.
Under the Hood
Kotlin's compiler parses expressions into a tree structure based on operator precedence and associativity. It uses this tree to generate code that evaluates operations in the correct order. Operators with higher precedence form deeper branches, ensuring they execute first. Parentheses create subtrees that override normal precedence.
Why designed this way?
This design follows decades of programming language tradition to keep expressions intuitive and consistent. Fixed precedence and associativity rules prevent ambiguity and make code easier to read and maintain. Allowing changes to precedence would cause confusion and bugs.
Expression parsing flow:

Input: 3 + 4 * 2

Parsing tree:

       (+)
      /   \
    (3)   (*)
          /  \
        (4)  (2)

Evaluation order:
1. Evaluate (*) node: 4 * 2 = 8
2. Evaluate (+) node: 3 + 8 = 11
Myth Busters - 4 Common Misconceptions
Quick: Does 3 + 4 * 2 equal 14 because addition comes first? Commit yes or no.
Common Belief:Some think operators are evaluated strictly left to right, so 3 + 4 * 2 equals 14.
Tap to reveal reality
Reality:Multiplication has higher precedence than addition, so 4 * 2 is done first, making the result 11.
Why it matters:Ignoring precedence leads to wrong calculations and bugs in programs.
Quick: Can parentheses be ignored without changing results? Commit yes or no.
Common Belief:Some believe parentheses are just for readability and don't affect calculation order.
Tap to reveal reality
Reality:Parentheses force the operations inside them to happen first, changing the result if used differently.
Why it matters:Misusing parentheses can cause unexpected results and logic errors.
Quick: Can you change operator precedence by overloading operators in Kotlin? Commit yes or no.
Common Belief:Some think operator overloading lets you change precedence or associativity.
Tap to reveal reality
Reality:Operator precedence and associativity are fixed in Kotlin and cannot be changed by overloading.
Why it matters:Trying to change precedence leads to confusing code and misunderstandings.
Quick: Does the assignment operator (=) have the same associativity as addition (+)? Commit yes or no.
Common Belief:Many assume all operators associate left to right.
Tap to reveal reality
Reality:Assignment operators associate right to left, meaning a = b = c assigns c to b first, then to a.
Why it matters:Misunderstanding associativity causes bugs in chained assignments.
Expert Zone
1
Some operators have the same precedence but different associativity, which affects evaluation order in subtle ways.
2
Unary operators like ++ and -- have higher precedence than binary operators, which can cause unexpected results if not carefully used.
3
Kotlin's fixed operator precedence ensures interoperability with Java and other JVM languages, maintaining consistent behavior.
When NOT to use
Operator precedence rules are fixed and should not be relied on for complex logic clarity. Instead, use parentheses to make the order explicit. For very complex expressions, breaking them into smaller statements improves readability and reduces errors.
Production Patterns
In real-world Kotlin code, developers use parentheses liberally to avoid ambiguity. Operator precedence knowledge helps in reading and debugging code but explicit grouping is preferred for maintainability. Overloading operators is common for domain-specific types but always respects Kotlin's precedence rules.
Connections
Mathematics order of operations
Operator precedence in programming directly builds on the math rules for order of operations.
Understanding math order of operations helps grasp why programming languages use precedence rules.
Parsing in compilers
Operator precedence guides how compilers parse expressions into syntax trees.
Knowing precedence helps understand compiler design and error messages related to expression parsing.
Legal contract clauses
Like operator precedence, legal contracts have clauses that must be interpreted in a specific order to avoid ambiguity.
Recognizing structured priority in language helps appreciate why programming languages enforce operator precedence.
Common Pitfalls
#1Ignoring operator precedence and expecting left-to-right evaluation.
Wrong approach:val result = 3 + 4 * 2 // expecting 14
Correct approach:val result = 3 + (4 * 2) // equals 11
Root cause:Misunderstanding that multiplication has higher precedence than addition.
#2Not using parentheses to clarify complex expressions.
Wrong approach:val value = 10 - 5 - 2 // unclear if (10 - 5) - 2 or 10 - (5 - 2)
Correct approach:val value = (10 - 5) - 2 // equals 3
Root cause:Not knowing associativity rules or how parentheses affect evaluation.
#3Trying to change operator precedence by overloading operators.
Wrong approach:operator fun MyType.plus(other: MyType): MyType { /* ... */ } // expecting different precedence
Correct approach:operator fun MyType.plus(other: MyType): MyType { /* ... */ } // precedence remains same as +
Root cause:Believing operator overloading can alter precedence or associativity.
Key Takeaways
Operator precedence defines the order in which operations are performed in expressions.
Multiplication and division have higher precedence than addition and subtraction in Kotlin.
Parentheses override precedence and force specific evaluation order.
Operators with the same precedence follow associativity rules to decide order.
Operator precedence is fixed in Kotlin and cannot be changed by overloading operators.