3

The Dart docs say that the 'new' operator is optional when instantiating an object from a class. It also says you can define a class to be a callable function by defining a Call() function within the class.

Given a class

Class MyClass

And i define both a constructor and Call() function within that class (neither of which has been defined to take any arguments)

what would the value of somevar be?

dynamic somevar = MyClass();

Would it be an instance of MyClass or would it be the return value of the Call() function?

Christopher Moore
  • 15,626
  • 10
  • 42
  • 52
  • check this `https://stackoverflow.com/questions/1053592/what-is-the-difference-between-class-and-instance-methods#:~:text=Like%20the%20other%20answers%20have,instance%20in%20as%20a%20parameter).` – Chandan Jan 14 '21 at 03:41
  • Nope, i don't see how this is relevant at all. My issue isn't understanding the difference between a callable class and a constructor. My issue is that it seems to me that the instantiation of a class and the calling of a callable class seems to have the exact same syntax. – mysticfakir Jan 14 '21 at 04:44

1 Answers1

2

The Dart Language Tour calls them "callable classes", but that's a misnomer. They're callable objects.

Typically call() is a method on an instance of the class, not on the class itself. MyClass() would always invoke the unnamed constructor of MyClass.

More concretely:

class MyClass {
  void call() {
    print('Hello world!');
  }
}

void main() {
  var object = MyClass(); // Invokes the (implicit) unnamed MyClass constructor.
  object(); // Invokes the call() method.
}
jamesdlin
  • 81,374
  • 13
  • 159
  • 204