Dart’s Callable Classes

Priyanka Tyagi
CodeChai
Published in
2 min readJun 14, 2020

--

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 a 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, 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 the code below. The addition object is of Addition type. Now, addition(1, 2) can be called to calculate the sum of the 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 check out the source code at Github here

References

  1. Function type
  2. Language Tour

Happy Darting :)

_Liked the article? Don’t forget to clap :)

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

Originally published at https://ptyagicodecamp.github.io on June 14, 2020.

--

--

Priyanka Tyagi
CodeChai

Tech explorer | Passionate about sharing explorations around software engineering and leadership