'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?
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Silvio Mayolo |
