🐦 Kotlin Intermediate

What is operator overloading in Kotlin?

Answer

Operator overloading lets you provide custom implementations for predefined operators for your own types. You mark a function with the operator modifier and use a specific function name corresponding to the operator: plus for +, minus for -, times for *, get/set for [], invoke for (), compareTo for comparison, etc. Example: operator fun Point.plus(other: Point) = Point(x + other.x, y + other.y) — now p1 + p2 works. Operator overloading should only be used when the operator has a clear, intuitive meaning for the type.