0
0
Kotlinprogramming~5 mins

Operator overloading concept in Kotlin

Choose your learning style9 modes available
Introduction

Operator overloading lets you use normal symbols like + or * with your own types. It makes your code easier to read and write.

When you create a class that represents numbers or math objects and want to add or multiply them easily.
When you want to compare two objects using <, >, == symbols naturally.
When you want to combine or modify objects using operators like +, -, or * instead of calling functions.
When you want your custom types to behave like built-in types in expressions.
When you want to make your code look clean and intuitive for others to understand.
Syntax
Kotlin
operator fun plus(other: ClassName): ClassName {
    // code to add this and other
    return result
}

The operator keyword tells Kotlin this function is for operator overloading.

You define functions with names like plus, minus, times to overload +, -, * respectively.

Examples
This lets you add two Point objects using the + operator.
Kotlin
operator fun plus(other: Point): Point {
    return Point(x + other.x, y + other.y)
}
This lets you multiply a Point by an integer using the * operator.
Kotlin
operator fun times(scale: Int): Point {
    return Point(x * scale, y * scale)
}
This lets you compare two Point objects using <, > operators.
Kotlin
operator fun compareTo(other: Point): Int {
    return this.x.compareTo(other.x)
}
Sample Program

This program creates a Point class with operator functions to add points and multiply by a number. It shows how to use + and * with Point objects.

Kotlin
data class Point(val x: Int, val y: Int) {
    operator fun plus(other: Point): Point {
        return Point(x + other.x, y + other.y)
    }

    operator fun times(scale: Int): Point {
        return Point(x * scale, y * scale)
    }
}

fun main() {
    val p1 = Point(2, 3)
    val p2 = Point(4, 5)
    val p3 = p1 + p2
    val p4 = p3 * 2
    println("p3 = $p3")
    println("p4 = $p4")
}
OutputSuccess
Important Notes

Only certain operators can be overloaded in Kotlin.

Operator functions must be marked with the operator keyword.

Overloading operators makes your code cleaner but use it only when it makes sense.

Summary

Operator overloading lets you use symbols like +, -, * with your own classes.

Use the operator keyword before functions like plus, times.

This makes your custom types easier and nicer to work with.