Callable Classes
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 84 of 110.
In Dart, you can make instances of a class callable like functions by implementing the call() method. This allows you to use an object with function call syntax - using parentheses directly on the instance.
class Multiplier {
final 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 the object like a function
print(triple(5)); // 15
}When you write double(5), Dart automatically invokes the call() method with 5 as the argument. The object behaves like a function while still maintaining its state (the factor field).
The call() method can have any signature - multiple parameters, optional parameters, or even return different types:
class Greeter {
final String greeting;
Greeter(this.greeting);
String call(String name, {String punctuation = '!'}) {
return '$greeting, $name$punctuation';
}
}
void main() {
var hello = Greeter('Hello');
print(hello('Alice')); // Hello, Alice!
print(hello('Bob', punctuation: '.')); // Hello, Bob.
}Callable classes are useful when you need function-like behavior combined with state or configuration. They're commonly used for creating reusable operations, validators, or transformations that need to remember settings between calls.
Challenge
EasyLet's build a text formatter system using callable classes! You'll create objects that can be called like functions to transform text in different ways, while maintaining their own configuration settings.
You'll organize your code into two files:
formatters.dart: Create two callable classes that transform text:- A
Wrapperclass that wraps text with a prefix and suffix. It should store aString prefixandString suffix, and when called with aString textparameter, return the text wrapped between the prefix and suffix. - A
Repeaterclass that repeats text a certain number of times. It should store anint timesvalue, and when called with aString textparameter, return the text repeated that many times with a space between each repetition.
- A
main.dart: Import your formatters and demonstrate how callable classes work:- Create a
Wrapperwith prefix"["and suffix"]" - Create another
Wrapperwith prefix"***"and suffix"***" - Create a
Repeaterthat repeats 3 times - 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 - Finally, combine them: call the first wrapper with the result of calling the repeater with
"Dart", and print the result
- Create a
Notice how each formatter object remembers its configuration and can be called directly with parentheses, just like a function!
Expected output:
[Hello]
***Important***
Go Go Go
[Dart Dart Dart]Cheat sheet
Classes can be made callable like functions by implementing the call() method:
class Multiplier {
final int factor;
Multiplier(this.factor);
int call(int value) {
return value * factor;
}
}
void main() {
var double = Multiplier(2);
print(double(5)); // 10 - calling the object like a function
}The call() method can have any signature with multiple parameters, optional parameters, or different return types:
class Greeter {
final String greeting;
Greeter(this.greeting);
String call(String name, {String punctuation = '!'}) {
return '$greeting, $name$punctuation';
}
}
void main() {
var hello = Greeter('Hello');
print(hello('Alice')); // Hello, Alice!
print(hello('Bob', punctuation: '.')); // Hello, Bob.
}Callable classes are useful for creating function-like behavior combined with state or configuration.
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 that repeats 3 times
// 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: Combine them: call the first wrapper with the result of
// calling the repeater with "Dart", 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