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?

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.

暂无
暂无

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

Related Question Overload cast operator in Kotlin How to properly overload an operator in kotlin Why do we use invoke operator overloading in Kotlin Usecases? Why Kotlin can not override List<*> operator method? Is it possible to overload function with receiver operator in Kotlin? Indexed access operator overload for a MutableList member in Kotlin Why can't we add block around property getter field in kotlin Why can't we use protected access modifier in Singleton class (object) for Kotlin Why doesn't this overload? Gradle + Kotlin why don't we assign variables directly
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM