call() Method
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 73 of 110.
Dart has a special method called call() that lets you use an object as if it were a function. When a class defines a call() method, you can invoke instances of that class using function call syntax.
class Multiplier {
int factor;
Multiplier(this.factor);
int call(int value) {
return value * factor;
}
}
void main() {
var double = Multiplier(2);
var triple = Multiplier(3);
print(double(5)); // 10 - calling object like a function
print(triple(5)); // 15
}Instead of writing double.call(5), you can simply write double(5). Dart automatically invokes the call() method when you use parentheses on the object.
The call() method can accept any parameters and return any type, just like a regular method:
class Greeter {
String prefix;
Greeter(this.prefix);
String call(String name, {String punctuation = '!'}) {
return '$prefix, $name$punctuation';
}
}
void main() {
var hello = Greeter('Hello');
print(hello('Alice')); // Hello, Alice!
print(hello('Bob', punctuation: '?')); // Hello, Bob?
}This pattern is useful when you need objects that behave like functions but also maintain state or configuration. It's commonly used for creating reusable operations, validators, or formatters that need to remember settings between calls.
Challenge
EasyLet's build a text formatter system where formatter objects can be called directly like functions! You'll create callable classes that transform text in different ways while maintaining their configuration settings.
You'll organize your code into two files:
formatters.dart: Create two callable classes that transform strings:- A
Wrapperclass that wraps text with a configurable prefix and suffix. It should storeprefixandsuffixstrings, and itscall()method should accept aString textand return the text wrapped with the prefix and suffix. - A
Repeaterclass that repeats text a configurable number of times. It should store atimesinteger, and itscall()method should accept aString textand return the text repeated that many times, separated by spaces.
- A
main.dart: Import your formatters and demonstrate how these objects can be used just like functions:- Create a
Wrapperwith prefix'['and suffix']' - Create another
Wrapperwith prefix'***'and suffix'***' - Create a
Repeaterwith times set to3 - Call the first wrapper with
'Hello'and print the result - Call the second wrapper with
'Important'and print the result - Call the repeater with
'Go'and print the result - Demonstrate chaining by passing the result of the first wrapper (with
'Nested') into the second wrapper, and print the result
- Create a
Notice how you can call your formatter objects directly using parentheses, just like regular functions. The call() method makes this possible, and each object remembers its configuration between uses!
Expected output:
[Hello]
***Important***
Go Go Go
***[Nested]***Cheat sheet
The call() method allows you to use an object as if it were a function. When a class defines a call() method, you can invoke instances of that class using function call syntax.
class Multiplier {
int factor;
Multiplier(this.factor);
int call(int value) {
return value * factor;
}
}
void main() {
var double = Multiplier(2);
print(double(5)); // 10 - calling object like a function
}Instead of writing double.call(5), you can simply write double(5). Dart automatically invokes the call() method when you use parentheses on the object.
The call() method can accept any parameters and return any type:
class Greeter {
String prefix;
Greeter(this.prefix);
String call(String name, {String punctuation = '!'}) {
return '$prefix, $name$punctuation';
}
}
void main() {
var hello = Greeter('Hello');
print(hello('Alice')); // Hello, Alice!
print(hello('Bob', punctuation: '?')); // Hello, Bob?
}This pattern is useful for creating objects that behave like functions but also maintain state or configuration between calls.
Try it yourself
import 'formatters.dart';
void main() {
// TODO: Create a Wrapper with prefix '[' and suffix ']'
// TODO: Create another Wrapper with prefix '***' and suffix '***'
// TODO: Create a Repeater with times set to 3
// TODO: Call the first wrapper with 'Hello' and print the result
// TODO: Call the second wrapper with 'Important' and print the result
// TODO: Call the repeater with 'Go' and print the result
// TODO: Demonstrate chaining by passing the result of the first wrapper
// (with 'Nested') into the second wrapper, and print the result
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesLibraries & ImportsIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsInstance VariablesConstructor BasicsRecap - Simple Calculator4Null Safety
Intro to Null SafetyNullable vs Non-NullableThe ? and ! OperatorsLate Keyword & Null SafetyNull-Aware OperatorsNull Safety in ClassesRecap - User Profile System7Abstract Classes & Interfaces
Abstract ClassesAbstract MethodsInterfaces in DartImplicit InterfacesImplementing vs ExtendingMultiple InterfacesRecap - Shape Calculator10Collections & Generics
List, Set, Map OverviewType-Safe CollectionsGeneric ClassesGeneric MethodsGeneric ConstraintsIterable & IteratorRecap - Generic Storage13Advanced OOP Concepts
Composition vs InheritanceExtension MethodsCallable ClassesSealed Classes (Dart 3)Records (Dart 3)Patterns & Matching (3.0)Enums with Methods16Project: Library Management
Project OverviewBook and User Classes2Constructors in Dart
Default ConstructorNamed ConstructorsInitializer ListsConstant ConstructorsFactory ConstructorsRedirecting ConstructorsRecap - Shape Builder5Encapsulation
Public vs Private MembersThe _ Prefix ConventionLibrary-Level PrivacyGetters & Setters DepthInformation HidingRecap - Student Records8Mixins
Introduction to MixinsCreating MixinsUsing Multiple Mixinson Keyword in MixinsMixin vs InheritanceMixin vs InterfaceRecap - Animal System11Special Methods
toString() OverridehashCode & == OverrideComparable Interfacecall() MethodnoSuchMethod OverrideRecap - Custom Collection14Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern3Class Properties
Instance vs Static MembersFinal & Const FieldsLate VariablesStatic Methods & FieldsGetters and SettersRecap - Bank Account Manager6Inheritance
Basic InheritanceThe super KeywordMethod OverridingThe @override AnnotationThe final Class KeywordConstructors & InheritanceRecap - Employee Hierarchy9Polymorphism
Polymorphism BasicsPolymorphism via InterfacesRuntime Type CheckingThe is & as OperatorsCovariant KeywordRecap - Payment Processor