generic
Generics in Dart allow you to write code that can work with different types while maintaining type safety. They provide a way to define classes, functions, and interfaces with type parameters. Here's an overview of how generics work in Dart:
Class Generics:
You can create generic classes by specifying one or more type parameters inside angle brackets (
<>
) after the class name. For example, here's a genericBox
class that can hold values of any type:In this example,
Box
is a generic class with a type parameterT
. You can create instances ofBox
with specific types, such asint
orString
.Function Generics:
Dart allows you to create generic functions by specifying type parameters for functions. Here's an example of a generic function that swaps the values of two variables:
In this example, the
swap
function is generic, and it works with any typeT
.Generic Interfaces:
Dart allows you to create generic interfaces or abstract classes. For example, the
List
class is a generic interface, and you can create lists of specific types:Type Bounds:
You can specify type bounds to restrict the types that can be used with generics. For example, you can specify that a generic type must implement a particular interface:
In this example, the
findFirst
function accepts a generic typeT
that must implement theComparable
interface.
Generics help improve code reusability and type safety by allowing you to write more flexible and generic code that can work with various data types while catching type errors at compile time.
Last updated