What are Generics?

In this lesson, you will learn about generics.

We'll cover the following

Introduction to Generics

Generics are used to apply stronger type checks at compile time. They enforce type-safety in code. For example, the type safety in collections is enforced by holding the same type of data. Generics help write reusable classes and methods/functions for different data types.

Type Safety: A programming concept that allows a memory block to contain only one type of data.

The concept of generics in Dart is similar to Java’s generics and C++'s templates.

Dart’s collection is able to hold different data types in one collection. It is optional in Dart to mention data type for a value. Usually, the variable’s data type is inferred automatically. For example, var myVar = 5; will infer myVar's data type as int. The code snippet below is valid in Dart. To verify Dart’s support for different data types, try to add/remove different data types. Add a list ['hello'] as an entry in the items list.

Get hands-on with 1200+ tech skills courses.