0
0
Kotlinprogramming~3 mins

Why operators are functions in Kotlin - The Real Reasons

Choose your learning style9 modes available
The Big Idea

What if the plus sign you use every day was actually a secret function you could customize?

The Scenario

Imagine you want to add two custom objects, like two points on a map, by writing code that just adds them with a plus sign.

Without operators as functions, you must write separate methods and call them explicitly, making your code long and hard to read.

The Problem

Manually calling methods like point1.add(point2) everywhere is slow to write and clutters your code.

It's easy to make mistakes or forget to call the right method, and your code looks less like natural math.

The Solution

Kotlin treats operators like + as special functions you can define for your own types.

This means you can write point1 + point2 and Kotlin calls your function behind the scenes, making code clean and intuitive.

Before vs After
Before
val result = point1.add(point2)
After
val result = point1 + point2
What It Enables

This lets you write code that reads like natural math or language, making it easier to understand and maintain.

Real Life Example

For example, in a game, you can add two vectors with vector1 + vector2 instead of calling a method, making your game logic clearer and simpler.

Key Takeaways

Operators in Kotlin are actually functions you can define.

This makes code shorter, clearer, and less error-prone.

You can use natural symbols like + with your own types.