0
0
Kotlinprogramming~5 mins

Why operators are functions in Kotlin

Choose your learning style9 modes available
Introduction

In Kotlin, operators are functions to make code clearer and let you customize how operators work with your own types.

When you want to add two numbers using the + operator.
When you want to compare two objects with ==.
When you want to define how your custom class adds or multiplies values.
When you want to use operators like [] to get or set values in your class.
When you want to make your code look simple but do complex actions behind the scenes.
Syntax
Kotlin
operator fun plus(other: Type): Type {
    // code to add
}

The operator keyword tells Kotlin this function works as an operator.

You can define functions for many operators like +, -, *, /, ==, [], and more.

Examples
This defines how to add two Point objects using +.
Kotlin
operator fun plus(other: Point): Point {
    return Point(x + other.x, y + other.y)
}
This lets you use square brackets [] to get values from your class.
Kotlin
operator fun get(index: Int): Int {
    return values[index]
}
Sample Program

This program shows how the + operator works as a function to add two points.

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 = (${p3.x}, ${p3.y})")
}
OutputSuccess
Important Notes

Operators as functions let you write clean and readable code.

You can customize operators for your own classes to make them easier to use.

Remember to use the operator keyword to enable operator overloading.

Summary

Operators in Kotlin are functions to keep code simple and flexible.

You can define how operators work with your own types using operator functions.

This helps make your code easier to read and write.