Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

128
Views
Why we can't overload operator = in Kotlin

It is more of a theory question because I am a little bit curious. For example in C++ you can do things like this with = operator (redone this example from some website)

class Counter {
public:
    Counter(int sec) {
        seconds = sec;
    }

    void display() {
        std::cout << seconds << " seconds" << std::endl;
    }

    Counter& operator = (int c2) {
        seconds = c2;
        return *this;
    }

    int seconds;
};

int main() {
    Counter c1(20);
    c1 = 10;
    c1.display();   // 10 seconds
    return 0;
}

In Kotlin we can overload operators with "operator fun", but there are no option for '='

What was the reason not to add it?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

C++ has value semantics for variables. So when you declare a variable x of type Foo, there's an actual Foo living in x. Not a pointer to it, not a reference, not some kind of shared object, but the actual memory for Foo. So if I do

Foo x = example1();
x = example2();

The Foo instance that's stored in x is the same chunk of memory, and it's that instance that gets to decide how the results of example2 get assigned to it. That's what operator= does.

Now, still in C++, consider

Foo* x = example1();
x = example2();

This is very different. Now x only stores a pointer: a simple numerical-ish value that points to the actual Foo. Then when I reassign it later, I'm actually getting a pointer to another, completely distinct Foo somewhere else in memory. In general, it has no relation to the original, and the Foo class doesn't get to decide how that pointer gets assigned; it just does. C++ decided what it means for pointers to assign to one another, not you and me mortal programmers.

Now, most higher-level languages (basically all of the languages you hear people talk about: Kotlin, Scala, Python, Ruby, Java, Lua, etc.) generally pass objects as pointers. So when you declare a variable of type Foo in Kotlin, it's basically a pointer to a Foo. And when you reassign that variable, you're reassigning the pointer. There's no way to do the equivalent of direct assignment in C++ in a high-level language like Kotlin.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!