
上QQ阅读APP看书,第一时间看更新
Callable classes
In the same way that Dart functions are nothing more than objects, Dart classes can behave like functions too, that is, they can be invoked, take some arguments, and return something as a result. The syntax for emulating a function in a class is as follows:
class ShouldWriteAProgram { // this is simple class
String language;
String platform;
ShouldWriteAProgram(this.language, this.platform);
// this special method named 'call' makes the class behave as a function
bool call(String category) {
if(language == "Dart" && platform == "Flutter") {
return category != "to-do";
}
return false;
}
}
main() {
var shouldWrite = ShouldWriteAProgram("Dart", "Flutter");
print(shouldWrite("todo")); // prints false.
// this function is invoking the ShouldWriteAProgram callable class
// resulting in a implicit call to its "call" method
}
As you can see, the shouldWrite variable is an object, an instance of the ShouldWriteAProgram class, but can also be called as a normal function passing a parameter and using its return value. This is possible because of the existence of the call() method defined in the class.
The call() method is a special method in Dart. Every class that defines it can behave as a normal Dart function.
If you assign a callable class to a function type variable, it will be implicitly converted into a function type and behave just like a normal function.