Callable Classes in Dart
Just like the functions, we can also call the instances of classes in Dart. Such classes are also known as “callable ” classes. We need to use the “call( )” function to implement the callable class.
Syntax :
class class_name
{
String call( < arguments > )
{
// body of the function
// return statement
}
main( )
{
// calling the instance just like the functions
}
Example – 1 :
// definition of the callable class
class Colour
{
// definition of the call( ) function
String call( String c_name, int hex_code )
{
return( ' The colour name is $c_name and the hexdecimal code is $hex_code ' ) ;
}
}
void main( )
{
// creating the object of the class ' colour '
Colour col = new Colour( ) ;
// calling the class instance just like a function
var info = col( ' Black ', 002147 ) ;
// printing the information about the colour
print( ' Dart Callable class ' ) ;
print( ' The information of the colour is : ' ) ;
print( info ) ;
}
Output :
Dart Callable class
The information of the colour is :
The colour name is Black and the hexdecimal code is 2147
Explanation :
In this code, we defined a call( ) function with return type ‘ String ’ and two arguments of type ‘ String ’ and ‘ int ’ in the ‘ Colour ’ class.
This call( ) method accepts the value of the colour name and it hexadecimal value in the arguments and return the print statement. Then, in the main( ) function, an object ‘ col ’ of the class ‘ Colour ’ is created and the instance of the class call( ) is called just like a function.
var infro = col( ' Sharma ',18 ) ;
Consider the following example in Dart that shows multiple callable classes
Example - 2 :
class Student
{
String call( String name, int age )
{
return( ' The student name is $name and the age is $age ' ) ;
}
}
class Teacher
{
String call( String t_name )
{
return( ' The name of the Teacher is : $t_name ' ) ;
}
}
void main( )
{
Student stu = new Student( ) ;
Teacher tem = new Teacher( ) ;
// calling the instance of the class ' Student ' just like a function
var s = stu( ' Yukta Malhotra ', 19 ) ;
// calling the instance of the class ' Teacher ' just like a function
var t = tem( ' Dimple Chawla ' ) ;
print( ' Multiple Callable classes in Dart ' ) ;
print( s ) ;
print( t ) ;
}
Output :
Multiple Callable classes in Dart
The student name is Yukta Malhotra and the age is 19
The name of the Teacher is : Dimple Chawla
Explanation :
In the above code, we defined two callable functions in class ‘ Student ’ and class ‘ Teacher ’. The ‘ Student ’ class has ‘ call( ) ’ function that accepts two parameters of data types ‘ String ’ and ‘ int ’. The ‘ Teacher ’ class has a ‘ call( ) ’ function that accepts only one parameter of type ‘ String ’. We called instances of both the classes as callable functions.
var s = stu( ' Yukta Malhotra ', 19 ) ;
var t = tem( ' Dimple Chawla ' ) ;