Callable Class
In this lesson, you will learn about the callable class.
We'll cover the following
Introduction
In Dart, functions are objects too. It is 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 a function. This feature of the Dart language is useful for making named-functions.
Implementing a callable Class
All Dart functions have a call
method. 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 a callable Class
Let’s check out using the Addition
callable class in the code below. The addition
object is of the Addition
type. Now, addition(1, 2)
can be called to calculate the sum of the given numbers.
Get hands-on with 1400+ tech skills courses.