Skip to Content
Course content

129: Operator Overloading in Kotlin

Click on the "Edit" button in the top corner of the screen to edit your slide content.

You've probably spent a lot of time writing methods like calculateTotal() or addPosition(). They work, but they can get wordy. In Kotlin, when we find ourselves writing methods that behave exactly like mathematical operators, we can use operator overloading. It's essentially a way of telling the compiler: "When you see a + sign between two objects of this class, actually call this specific function."

I'm a big fan of this for domain-specific logic. To show you how it works, let's build a simple Vector2D class. If you've ever done game dev or basic physics, you know that adding two vectors or scaling one by a number is a constant task. Writing v1.add(v2) is fine, but v1 + v2 is just cleaner.

Defining the Vector and the plus operator

First, we'll start with a basic data class. To overload the + operator, we need to implement a function called plus and mark it with the operator keyword. If you forget that keyword, Kotlin will just treat it as a regular function and the + symbol won't work.

data class Vector2D(val x: Double, val y: Double) {
    operator fun plus(other: Vector2D): Vector2D {
        return Vector2D(this.x + other.x, this.y + other.y)
    }
}

fun main() {
    val pos1 = Vector2D(10.0, 5.0)
    val pos2 = Vector2D(2.0, 3.0)
    
    // This now calls the plus() function under the hood
    val result = pos1 + pos2 
    println(result) // Vector2D(x=12.0, y=8.0)
}

The "Why isn't this compiling?" moment

Now, I want to be able to scale my vector. For example, if I have a direction vector and I want to multiply its length by 2. I'll try to implement a times function to handle the * operator. I'll write it quickly, just like I often do when I'm in a flow state:

// Inside Vector2D
fun times(scalar: Double): Vector2D {
    return Vector2D(this.x * scalar, this.y * scalar)
}

When I try to run val scaled = pos1 * 2.0, the compiler screams at me. It tells me that the * operator isn't defined for these types. I've made the classic mistake: I named the function times, but I forgot the operator modifier. In Kotlin, naming a function plus or times isn't enough; the modifier is what actually "hooks" the symbol to the function.

Fixing the scaling logic

Let's fix that and add one more thing. I want to be able to multiply the vector by a scalar regardless of whether the scalar comes first or second (e.g., vector * 2 and 2 * vector). To do the latter, I can define a top-level function or an extension function.

data class Vector2D(val x: Double, val y: Double) {
    operator fun plus(other: Vector2D): Vector2D {
        return Vector2D(this.x + other.x, this.y + other.y)
    }

    // Fixed: added the operator keyword
    operator fun times(scalar: Double): Vector2D {
        return Vector2D(this.x * scalar, this.y * scalar)
    }
}

// This allows us to do: 2.0 * vector
operator fun Double.times(vector: Vector2D): Vector2D {
    return vector.times(this)
}

fun main() {
    val v = Vector2D(1.0, 2.0)
    println(v * 3.0)     // Vector2D(x=3.0, y=6.0)
    println(3.0 * v)     // Vector2D(x=3.0, y=6.0)
}

Just a quick word of caution: don't overdo this. If you start overloading the minus operator to mean "delete a user from a database," your teammates will hate you. Only use operator overloading when the symbol's meaning is intuitive and mathematically sound.




📋 Practical Task

Implementing a ComplexNumber Arithmetic Class

In mathematics, complex numbers have a real part and an imaginary part (represented as a + bi). Your task is to create a class that makes working with these numbers feel natural using operator overloading.

Requirements:

  • Create a data class ComplexNumber with two properties: real (Double) and imaginary (Double).
  • Overload the plus (+) operator to add two complex numbers. (The formula is: (a+bi) + (c+di) = (a+c) + (b+d)i).
  • Overload the minus (-) operator to subtract two complex numbers. (The formula is: (a+bi) - (c+di) = (a-c) + (b-d)i).
  • Overload the times (*) operator to multiply a ComplexNumber by a Double scalar.

Test your implementation in a main function by creating two complex numbers, adding them, subtracting one from the other, and scaling one by a factor of 2.0.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.