![]() |
VOOZH | about |
Dart allows the user to create a callable class which allows the instance of the class to be called as a function. To allow an instance of your Dart class to be called like a function, implement the call() method.
Syntax :
class class_name {
... // class content
return_type call ( parameters ) {
... // call function content
}
}
In the above syntax, we can see that to create a callable class, we have to define a call method with a return type and parameters within it.
Example :
Output:
Welcome to GeeksForGeeks!Note: It must be noted that Dart doesn't support multiple callable methods i.e. if we try to create more than one callable function for the same class it will display error.
Example :
Output:
compileDDC
main.dart:7:10: Error: 'call' is already declared in this scope.
String call(String a) => 'Welcome to $a!';
^^^^
main.dart:4:10: Context: Previous declaration of 'call'.
String call(String a, String b, String c) => 'Welcome to $a$b$c!';
^^^^
- A callable class in Dart is a class that can be invoked like a function. To create a callable class, you must define a call method inside the class. The call method can take any number of arguments and return any type of value.
- You can also define a call method inside an anonymous function, which allows you to create a callable function on the fly. Here is an example:
Example:
Output:
3