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 genericBoxclass that can hold values of any type:class Box<T> { T value; Box(this.value); } void main() { var intBox = Box<int>(42); var stringBox = Box<String>('Hello, Dart!'); }In this example,
Boxis a generic class with a type parameterT. You can create instances ofBoxwith specific types, such asintorString.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:
T swap<T>(T a, T b) { return b; } void main() { var a = 1; var b = 2; a = swap<int>(a, b); print('a: $a, b: $b'); // Output: a: 2, b: 2 }In this example, the
swapfunction is generic, and it works with any typeT.Generic Interfaces:
Dart allows you to create generic interfaces or abstract classes. For example, the
Listclass is a generic interface, and you can create lists of specific types:List<int> numbers = [1, 2, 3]; List<String> names = ['Alice', 'Bob', 'Charlie'];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:
T findFirst<T extends Comparable<T>>(List<T> list) { if (list.isEmpty) { throw ArgumentError('List is empty'); } return list.reduce((value, element) => value.compareTo(element) < 0 ? value : element); } void main() { var numbers = [3, 1, 4, 1, 5, 9]; var result = findFirst(numbers); print('First minimum number: $result'); // Output: First minimum number: 1 }In this example, the
findFirstfunction accepts a generic typeTthat must implement theComparableinterface.
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