Generics in Dart — Part I

Intro to generics in Dart.

Tarun Chawla
2 min readMay 7, 2022

We will discuss the below topics in two parts:

  1. Intro to Generics for creating generic classes and functions.
  2. How does it fit in the Dart type system (you can read it as Subtyping in Dart if you are coming from the Java world)?

In this, we will solely focus on 1.

Generics are often used for primarily two purposes:

  1. To reduce code duplication.
  2. Better generated code.

How to create a Generic class?

Let us suppose there are no generics in Dart and you need to create an interface for a cache which simply stores a value for a key. Either you will use dynamic or spend all day creating abstract classes for different types e.g ObjectCache & StringCache.

Now let’s see how we will use generics here. The annotation <..> marks a class as a generic type. By convention, most type variables have single-letter names such as E, K & T etc.

Replacing concrete type with type variable T we are able to create a Cache class via which we can create Cache for any type without rewriting the interface again and again for different types. Below is an example of how you create StringCache which extends the generic Cache interface.

Similarly we can implement concrete generic class, lets take example of Stack.

Try it: https://dartpad.dev/?id=b6aad6a72bb3ffadb4a6e3b9041ad97b

How to create generic methods?

Earlier Dart used to support only class generics but now it supports generic methods as well. Below is one example:

Try it: https://dartpad.dev/?id=a182d6d0b548bc61444875dc0f4d465a

Restricting the parameterized type

Sometimes you might want to restrict the type user of your generic type can provide.

A common use case is to prevent nullable type from being passed as a type parameter by making it a subtype of Object. Here are a few examples:

References:

  1. Part-II : https://tarunengineer.medium.com/soundness-generics-in-dart-part-ii-56259a20fb2c
  2. https://dart.dev/guides/language/language-tour#generics

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response