Callable Objects : Different ways to “call” function or objects in Dart

Rahul Dev
2 min readMar 16, 2024

--

In Dart all the datatypes are classes and objects. I mean the data types like, int you may think its a primitive data type, but its NOT. Its a class, and when we are taking,

int myVariable = 20

We are actually creating an object of class int .

Now let’s consider functions in dart. Every function we use in dart is basically an object of class Function. But then function has its unique property, so that we can call that function. let’s take 2 code snippets.

///CODE SNIPPET 1

void myFunction() {
print('you have called myFunction');
}

void main() {
myFunction();
}
///CODE SNIPPET 2

final Function myFunction = () {
print('you have called myFunction');
};

void main() {
myFunction();
}

In Code Snippet 1 its simple function declaration named myFunction,
On the other hand in Code Snippet 2, in its a variable called myFunction of type class Function and assigned an anonymous function to it.
Above both code snippet are very same and runs in the same way.

Now you can understand myFunction is an object of class Function, however you have declared it.

If so, then how we are calling and object ? i.e, myFunction().

The answer is, thats possible because of a special method call().

So, in above code snippets you could have also written myFunction.call(); inside main instead of myFunction();.

So, Dart supports callable objects. That means if inside any class call method is declared then you can call an object of that class.

Lets take an example,

class Square{
int call(int input) => input * input;
}

Now we have made a class Square that can do suare of any number.

main() {
Square squareObj = Square();
int result = squareObj(5);
print(result);
}

It will give output 25.

Here is a screenshot from DartPad.

Now you can play around this.

You can declare a anonymous function and call that immediately.

main() {
(){
int a = 5, b = 8;
int sum = a + b;
print(sum);
}.call();
}

Or,

main() {
(){
int a = 5, b = 8;
int sum = a + b;
print(sum);
}();
}

It will give output 13

Take another little tricky one,

main() {
(int a, int b){
int sum = a + b;
print(sum);
}(5, 8);
}

This will also give output in 13. Here we are declaring a anonymous function and then calling it by passing the parameters. immediately.

One very good use case of this in flutter I had a medium blog,

refer The ((){}()) widget in above blog.

--

--

Rahul Dev

Software Engineering Specialist at BT Group ◇ Ex-SSE at LendingKart, Mantra Labs