Bird
Raised Fist0
Kotlinprogramming~10 mins

Operator overloading concept in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Operator overloading concept
Define class with operator function
↓
Create objects of class
↓
Use operator symbol between objects
↓
Compiler calls operator function
↓
Return result of operation
↓
Use result in program
Operator overloading lets you use symbols like + or * with your own classes by defining special functions.
Execution Sample
Kotlin
data class Point(val x: Int, val y: Int) {
    operator fun plus(other: Point) = Point(x + other.x, y + other.y)
}

val p1 = Point(1, 2)
val p2 = Point(3, 4)
val p3 = p1 + p2
This code adds two Point objects using the + operator overloaded by the plus function.
Execution Table
StepActionEvaluationResult
1Create p1Point(1, 2)p1 = Point(1, 2)
2Create p2Point(3, 4)p2 = Point(3, 4)
3Evaluate p1 + p2Calls p1.plus(p2)Calls plus function
4Inside plus functionx + other.x = 1 + 3, y + other.y = 2 + 4Returns Point(4, 6)
5Assign result to p3p3 = Point(4, 6)p3 = Point(4, 6)
6EndNo more operationsExecution stops
💡 No more operations to perform, program ends
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 5Final
p1undefinedPoint(1, 2)Point(1, 2)Point(1, 2)Point(1, 2)
p2undefinedundefinedPoint(3, 4)Point(3, 4)Point(3, 4)
p3undefinedundefinedundefinedPoint(4, 6)Point(4, 6)
Key Moments - 3 Insights
Why does p1 + p2 call the plus function?
Because the plus function is marked with the operator keyword, Kotlin knows to use it when + is used between Point objects (see Step 3 in execution_table).
What happens if we don't define the plus operator function?
The + operator won't work with Point objects and will cause a compile error, since Kotlin doesn't know how to add them (no operator function called).
Does operator overloading change the meaning of + globally?
No, it only changes how + works for the specific class where you define the operator function (here, Point). Other types keep their usual + behavior.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of p3 after Step 5?
APoint(3, 4)
BPoint(1, 2)
CPoint(4, 6)
Dundefined
💡 Hint
Check the 'Assign result to p3' row in execution_table where p3 is set to Point(4, 6).
At which step does the plus function actually compute the new Point?
AStep 3
BStep 4
CStep 2
DStep 5
💡 Hint
Look at Step 4 in execution_table where the plus function adds coordinates and returns Point(4, 6).
If we remove the operator keyword from the plus function, what happens when running p1 + p2?
ACompile error, + operator not recognized for Point
BIt works the same, calling plus function
CRuntime error when adding points
Dp1 and p2 are concatenated as strings
💡 Hint
Operator keyword tells Kotlin to use plus with +; without it, + is unknown for Point (see key_moments).
Concept Snapshot
Operator overloading in Kotlin lets you define how operators like + work with your classes.
Use the operator keyword before a function (e.g., operator fun plus(other: Type)).
When you use + between objects, Kotlin calls this function.
This makes your classes behave more naturally with operators.
Without operator keyword, operators won't work with your class.
Full Transcript
Operator overloading in Kotlin allows you to use standard operators like + with your own classes by defining special functions marked with the operator keyword. In the example, a Point class defines operator fun plus to add two points. When you write p1 + p2, Kotlin calls p1.plus(p2) behind the scenes, returning a new Point with summed coordinates. Variables p1 and p2 hold the original points, and p3 holds the result. This process is shown step-by-step in the execution table. Key points include that the operator keyword is necessary for Kotlin to recognize the function as an operator, and that operator overloading only affects the class where it is defined. Without it, using + on Point objects causes a compile error. This makes your classes easier and more natural to use with operators.

Practice

(1/5)
1. What does operator overloading in Kotlin allow you to do?
easy
A. Disable operators for certain classes
B. Change the meaning of built-in types like Int or String
C. Create new operators not available in Kotlin
D. Use standard operators like + or * with your own classes

Solution

  1. Step 1: Understand operator overloading purpose

    Operator overloading lets you define how operators like + work with your own classes.
  2. Step 2: Check options meaning

    Only Use standard operators like + or * with your own classes correctly states this ability. Options A, B, and C are incorrect because Kotlin does not let you change built-in types, create new operators, or disable operators this way.
  3. Final Answer:

    Use standard operators like + or * with your own classes -> Option D
  4. Quick Check:

    Operator overloading = Use operators with custom classes [OK]
Hint: Operator overloading means using +, * with your own classes [OK]
Common Mistakes:
  • Thinking you can create new operators
  • Believing it changes built-in types
  • Confusing disabling operators with overloading
2. Which of the following is the correct syntax to overload the plus operator in a Kotlin class?
easy
A. operator fun plus(other: MyClass): MyClass { ... }
B. fun plus(other: MyClass): MyClass { ... }
C. override fun plus(other: MyClass): MyClass { ... }
D. fun operator plus(other: MyClass): MyClass { ... }

Solution

  1. Step 1: Recall operator function syntax

    In Kotlin, to overload an operator, the function must be marked with the keyword operator before the function declaration.
  2. Step 2: Analyze options

    operator fun plus(other: MyClass): MyClass { ... } correctly uses operator fun plus(...). fun plus(other: MyClass): MyClass { ... } misses the operator keyword, C wrongly uses override, and D has incorrect keyword order.
  3. Final Answer:

    operator fun plus(other: MyClass): MyClass { ... } -> Option A
  4. Quick Check:

    Operator keyword before function = Correct syntax [OK]
Hint: Always put 'operator' before function to overload operators [OK]
Common Mistakes:
  • Omitting the 'operator' keyword
  • Using 'override' instead of 'operator'
  • Placing 'operator' after 'fun'
3. What will be the output of this Kotlin code?
data class Point(val x: Int, val y: Int) {
    operator fun plus(other: Point) = Point(x + other.x, y + other.y)
}

fun main() {
    val p1 = Point(1, 2)
    val p2 = Point(3, 4)
    val p3 = p1 + p2
    println(p3)
}
medium
A. Point(x=4, y=6)
B. p1 + p2
C. Compilation error
D. Point(4, 6)

Solution

  1. Step 1: Understand operator plus function

    The plus operator adds the x and y values of two Point objects and returns a new Point with summed coordinates.
  2. Step 2: Calculate the result of p1 + p2

    p1 has (1, 2), p2 has (3, 4). Adding gives (4, 6). Printing p3 calls data class's toString(), which outputs 'Point(x=4, y=6)'.
  3. Final Answer:

    Point(x=4, y=6) -> Option A
  4. Quick Check:

    p1 + p2 = Point(x=4, y=6) [OK]
Hint: Data class toString shows property names; sum coordinates [OK]
Common Mistakes:
  • Expecting just coordinates without property names
  • Thinking '+' prints expression instead of result
  • Assuming compilation error without operator keyword
4. Identify the error in this Kotlin code that tries to overload the minus operator:
class Counter(var count: Int) {
    fun minus(other: Counter): Counter {
        return Counter(count - other.count)
    }
}
medium
A. Wrong return type; should be Int instead of Counter
B. Missing 'operator' keyword before the minus function
C. Function name should be 'operatorMinus' instead of 'minus'
D. Cannot overload minus operator for classes

Solution

  1. Step 1: Check operator overloading syntax

    To overload an operator in Kotlin, the function must have the 'operator' keyword before its declaration.
  2. Step 2: Analyze the code

    The minus function lacks the 'operator' keyword, so Kotlin won't treat it as operator overloading, causing errors when using '-'.
  3. Final Answer:

    Missing 'operator' keyword before the minus function -> Option B
  4. Quick Check:

    Operator functions need 'operator' keyword [OK]
Hint: Operator functions must start with 'operator' keyword [OK]
Common Mistakes:
  • Forgetting the 'operator' keyword
  • Changing function name incorrectly
  • Assuming operator overloading is not allowed
5. Given this Kotlin class:
class Vector(val x: Int, val y: Int) {
    operator fun plus(other: Vector) = Vector(x + other.x, y + other.y)
    operator fun times(scalar: Int) = Vector(x * scalar, y * scalar)
}

What is the result of this expression?
val v1 = Vector(2, 3)
val v2 = Vector(1, 1)
val result = (v1 + v2) * 2
println("(${result.x}, ${result.y})")
hard
A. (3, 4)
B. (4, 6)
C. (6, 8)
D. Compilation error due to operator precedence

Solution

  1. Step 1: Evaluate v1 + v2

    v1 is (2,3), v2 is (1,1). Adding gives Vector(3,4).
  2. Step 2: Multiply the result by 2

    Vector(3,4) times 2 gives Vector(6,8).
  3. Step 3: Print the result

    Printing prints (6, 8) as expected.
  4. Final Answer:

    (6, 8) -> Option C
  5. Quick Check:

    (v1 + v2) * 2 = (6, 8) [OK]
Hint: Evaluate plus first, then times; operator overloading respects precedence [OK]
Common Mistakes:
  • Multiplying v2 by 2 instead of the sum
  • Ignoring operator precedence
  • Expecting compilation error
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard