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…

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).

Leave a Reply