concept generic in category dart

appears as: generics
Dart in Action

This is an excerpt from Manning's book Dart in Action.

In practice, though, avoid using the dynamic keyword explicitly, unless you provide adequate code comments explaining your decision to use dynamic. As with all rules, there’s an exception, which we’ll look at in more depth when we start to use generics in chapter 8.

That was a long section, but generics and collections are powerful features of Dart and (like superheroes) become even more powerful when combined. Generics aren’t restricted to being used with collections, though. In the next section, we’ll look at how to create your own “generic” classes that let you use type placeholders in your class but let users of your class create their own strongly typed versions.

The first thought is to subclass User and have RolesUser and PermissionsUser, each with its own add() method and so on, as shown in figure 8.9. Fortunately, before going down this route, you remember generics and decide that this situation would be a perfect fit for the creation of a generic user class.

Figure 8.9. If you find yourself creating several similar classes that use slightly different objects but in the same way, then you could have a case for using generics.

Fortunately, Dart has generics built into the type system. A generic type is a way of defining a class in a general, or generic, way but allowing the user of the class to use it in a specific way, even though there’s no shared type hierarchy such as a list of Permissions, a list of Strings, and a list of ints.

All the types in the Collection hierarchy have been written using generics, which allows you to use them specifically for your Permission class. In other words, you can create a list of Permissions, and Dart’s type checker can then flag errors such as accidentally adding a String into your list.

Classes built using generics take the form Name<T>, where Name is the name of the class or interface and T is a comma-separated list of type placeholders. The collection classes that you’ve seen so far have generic signatures, as shown in figure 8.6, where E represents a placeholder for the Element type.