0
0
KotlinConceptBeginner · 3 min read

What is Operator Function in Kotlin: Simple Explanation and Example

In Kotlin, an operator function lets you define or change how standard operators like +, -, or * work with your own classes. You mark a function with the operator keyword to tell Kotlin to use it when that operator is applied to your objects.
⚙️

How It Works

Think of an operator function as teaching Kotlin how to handle math or comparison symbols when you use your own custom objects. Normally, operators like + or * work with numbers, but with operator functions, you can tell Kotlin what + means for your special class.

For example, if you have a class representing a point on a map, you can define what adding two points means by writing an operator function. When Kotlin sees the + symbol between two points, it calls your function behind the scenes.

This works by marking a function with the operator keyword and giving it a special name that matches the operator you want to support. Kotlin then links the operator symbol to your function automatically.

💻

Example

This example shows a simple Point class where we define how to add two points using an operator function.

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

fun main() {
    val p1 = Point(2, 3)
    val p2 = Point(4, 5)
    val p3 = p1 + p2
    println(p3)
}
Output
Point(x=6, y=8)
🎯

When to Use

Use operator functions when you want your custom classes to behave like built-in types with operators. This makes your code cleaner and easier to read.

Common cases include math objects like vectors, points, or matrices, where adding or multiplying makes sense. You can also use operator functions for comparisons, indexing, or invoking objects like functions.

For example, if you create a class for complex numbers, defining operator functions for + and * lets you write natural expressions like c1 + c2 instead of calling methods.

Key Points

  • Operator functions let you customize how operators work with your classes.
  • You mark them with the operator keyword and use special function names.
  • This improves code readability by allowing natural operator usage.
  • Common operators you can overload include plus, minus, times, get, and invoke.

Key Takeaways

Operator functions let you define how operators like + or * work with your custom classes.
Use the operator keyword before a function to enable operator overloading in Kotlin.
This feature makes your code more natural and easier to read when working with custom types.
Common use cases include math objects, collections, and callable objects.
Remember to keep operator functions intuitive to avoid confusing code.