CodeBlanks Logo Icon CodeBlanks

Extension method

Learn to write extension methods.

Extension method

An extension method is a method declared inside an extension. It is accessed via this on an instance of the target type. The extension StringRepeat on String { String repeat(int n) => ... } declaration enables the call 'ab'.repeat(3).

Extension methods are used like class methods. However, they cannot be overridden or modified in subclasses. This is because extensions are resolved statically at compile time; there is no dynamic dispatch (polymorphism).

this and extension

Inside an extension method, this refers to the instance the method was called on. In extension on int { int doubled() => this * 2; }, this is the int value called. In 5.doubled(), this is 5.

Extension methods can call other methods in the same extension. Also, multiple methods can be declared inside an extension. The extension name is only for documentation and conflict avoidance; it doesn't affect the call.

Practice A ListSum extension

Define a ListSum extension on List<int> with an int total() => fold(0, (a, b) => a + b); method. In main add print([1, 2, 3].total());.

Starter code

main.dart
void main() {
  // define a ListSum extension (on List<int>; total method)
  // print [1, 2, 3].total()
}

Sample solution

main.dart
extension ListSum on List<int> {
  int total() => fold(0, (a, b) => a + b);
}

void main() {
  print([1, 2, 3].total());
}

Expected output

6

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 An extension method call

Question
final result = 'ab'.____(3);
print(result);
Answer
final result = 'ab'.repeat(3);
print(result);

Explanation: 'ab'.repeat(3) calls the extension method.

2 How are extension methods resolved?

  • Statically at compile time Correct answer
  • Only in subclasses
  • Dynamically at runtime
  • Never resolved

Explanation: extension methods are resolved statically at compile time.

3 Match the extension method parts

Term Meaning
this Called instance
on Type Target type
static Resolution style
override Invalid

All lessons in Expert