Callable classes in Dart

Published on 29 March 2020
Last Updated on 29 March 2020

If a class implements the call() method then its instance can be called as a function and the class is called callable class.

Refer to program given below to understand how callable classes can be used in a real program.

Program using callable class

class Hello {
  // this makes class callable
  String call(String message1, String message2) {
    return '${message1} ${message2}';

main(List<String> args) {
  var hello = new Hello();

  // called as a function
  var finalMessage = hello('hello', 'world');

Above program produces following output:

hello world

Program explanation: As you can see, above code defines a callable Hello that implements a call() method that accepts two String parameters.

This instance method can be called by creating an instance of the class and then treating instance of the class as a function.