Dart's Callable Classes

Posted on June 14, 2020 in Dart

enums

Introduction

In Dart, functions are objects too. It's an object of type Function. Similar to other objects, functions can be passed as arguments to other functions, and can be assigned to variables as well.

A Callable class allows its instance to be called as function. This feature of Dart language is useful in making named-functions.


Check out YouTube Video


Implementing Callable Class

All Dart functions have call method. In order to make a class Callable, the call() method needs to be implemented. Let's declare a callable class below:

class Addition {
  int call(int a, int b) => a + b;
}

The above class' call method takes two arguments and returns their sum.


Using Callable Class

Let's check out using the Addition callable class in code below. The addition object is of Addition type. Now, addition(1, 2) can be called to calculate the sum of given numbers.

void main() {
  Addition addition = Addition();
  var result = addition(1, 2);
  print(result);
}

Output:

3

Summary

In this article, we learned that Dart is a true object-oriented language. Dart's functions are also objects. We learned to implement a callable class.

That's it for this article. Check out the Dart Vocabulary Series for other Dart stuff.


Source Code

Please checkout the source code at Github here


References

  1. Function type
  2. Language Tour

Happy Darting :)

_Liked the article? Couldn't find a topic of interest? Please leave a comment or reach out at twitter about the topics you would like me to share!

BTW I love cupcakes and coffee both :)_

Follow me at Medium