CodeBlanks Logo Icon CodeBlanks

Summary - Native extension

Combine extension methods, operators and generics to write a string helper extension.

Summary: Native extension

In this group we covered Dart extensions: an extension adds external methods to an existing type; an extension method accesses via this; an extension operator overloads operators.

A generic extension takes a type parameter; the extension vs subclass decision depends on state and polymorphism. In this summary you will write a string helper extension that combines all of these concepts.

Practice Summary: A StringEx extension

Define a StringEx extension on String with two methods: String shout() => toUpperCase() + '!'; and int wordCount() => split(' ').length;. In main add print('hello world'.shout()); and print('hello world'.wordCount());.

Starter code

main.dart
void main() {
  // define a StringEx extension (on String; shout and wordCount)
  // print shout and wordCount calls
}

Sample solution

main.dart
extension StringEx on String {
  String shout() => toUpperCase() + '!';
  int wordCount() => split(' ').length;
}

void main() {
  print('hello world'.shout());
  print('hello world'.wordCount());
}

Expected output

HELLO WORLD!
2

Questions and answers

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

1 How are extension methods resolved?

  • Statically at compile time Correct answer
  • Never resolved
  • Dynamically at runtime
  • In a subclass

Explanation: extension methods are resolved statically at compile time.

2 Match the extension concepts

Term Meaning
extension method This access
extension operator Operator overloading
generic extension Type parameter
subclass Inheritance and polymorphism

3 An extension name

Question
extension ____ on String {
  String shout() => toUpperCase() + '!';
}
Answer
extension StringShout on String {
  String shout() => toUpperCase() + '!';
}

Explanation: StringShout is the extension's name.

All lessons in Expert