Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What does `operator () { … }` do in Dart?

Here is a simple dart class:

class MyOperatorClass {
    int operator () {
        return 5;
    }
}

I noticed today that this compiles without any issues. This led me to wonder, what does operator () mean?

Usually in dart, you use operator to implement, well, operators. Aka operator +(other) or operator ~(). But operator () doesn’t seem to have an operator associated with it…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

At first I thought it was how you make objects callable, but as it turns out, MyOperatorClass()() doesn’t compile (this is because callable objects actually implement the call() method). I asked ChatGPT about this and it was thoroughly confused, going back and forth on whether or not operator () was a valid way to create callable objects, haha.

So if it’s not how you create callable objects, but it does compile, what is it actually doing? When would it ever run?

>Solution :

In this case, you’re declaring an ordinary method that happens to be named operator. You’d call it like any other named method:

void main() {
  var x = MyOperatorClass();
  print(x.operator()); // Prints: 5
}

From https://dart.dev/language/keywords, note that operator is listed with 2:

Words with the superscript 2 are built-in identifiers. These keywords are valid identifiers in most places, but they can’t be used as class or type names, or as import prefixes.

So operator apparently is legal as a method name (although using that would be ill-advised).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading