What is Dart call()?

In Dart, all functions are objects with type Function since Dart is a pure object-oriented language. All functions inherently have the call method. The call method is used to call a function like someFunction(). This is the same as writing someFunction.call(). In fact, when an object is called the compiler, it checks if the object has a call method.

All Function objects have the call method
All Function objects have the call method

Classes as functions

You can write functions as classes by explicitly including the call method. Just like you would if you were writing a class, you can have and initialize private members of a function.

Code

In the example below, we have a conversation between two people. Using our Greet function we can set up a custom greeting by writing:

Greet hello = new Greet('Hello');

Every time we use hello after this instance, it will use our custom greeting of ‘Hello’. Notice how our Greet class acts like a function. That’s because it uses the call method.

We follow-up on the greeting by calling the followUp function, which uses your typical function syntax. Notice how we can use both followUp('John') and followUp.call('John') to the same effect even though followUp does not explicitly state the call method explicitly stated.

import 'dart:convert';
class Greet implements Function {
String _greeting;
Greet(this._greeting);
call(String name) {
return _greeting + ' ' + name;
}
// alternative syntax for function
// call(String name) => _greeting + ' '+ name;
// => is equivalent to the return statement
}
String followUp(String name) => 'Hey ' + name;
void main() {
Greet hello = new Greet('Hello');
print(hello('Ali'));
print(followUp.call('John'));
// you can call followUp('John') as well
// call is implicitly called
}
Copyright ©2024 Educative, Inc. All rights reserved