Generics in dart
Hello! In this article, you’ll learn how to use the Dart generics. After reading this article you can easily use dart generics in your code.
Why we need Dart generics ?
Suppose you need a class that represents a pair of values with the same type, for example, a pair of integers or a pair of strings.
To do that, you need to define different classes, one for a pair of integer and another for a pair of strings.
For example:
class IntPair {
int x;
int y;
IntPair(this.x, this.y);
}
class StringPair {
String x;
String y;
StringPair(this.x, this.y);
}
This solution is not scalable, here using dart generic.
For example, the following defines a class that represents a pair of values with the same type:
class Pair<T> {
T x;
T y;
Pair(this.x, this.y);
}
领英推荐
The letter T inside the angle brackets <> is the type. By convention, type variables have single-letter names like T,R, E, S, K, and V.
To create a pair of integers, you specify int as the type T when creating a new Pair object:
var pairInt = Pair<int>(10, 20);
print('x=${pairInt.x},y=${pairInt.y}');
// Output: x=10,y=20
Now we will take one more example, We will create a function which can take any type of data and print age.
printAge<String>("Not defined");
printAge<int>(45);
printAge<List>([4,5,6]);
Output:
Age: Not defined
Age: 45
Age: [4, 5, 6]
void printAge<R>(R age){
print("Age: $age") ;
}
printAge function takes a R type of argument and print it, Its very easy to understand.
When we call printAge function then we should add type using angle brackets <> it's not compulsory to add type, but in my opinion we should add it because it gives clear idea about a return type of function & It comes under the dart good practices.
Thank you guys for reading article, If you have any doubt than you can ask on my linkedin .
Attended Delhi University
1 年???????????? ???????? ???????? ?????????? concept ??( ?????????? ?????????????????? ) ????????. : ??-?? ?????? (Flexible hrs) ???????????? : 25,000/- ???? 30,000/ ?????? ?????????? ?????? : 18+ ?????????????????? :???????? ???? ?????? ???????????? ???????? : ???????? ???????? ??????e ???????????????????????? : ???????????????????? ?????? ???????? ???????????????? ????????????????????. ??????????, ??????????????, ????????????????, ????????????????????, ?????????????????????? ??????????????, ???????????? ?????? ???????? ???? ?????? ?????? ???????????????????? Register below????????https://docs.google.com/forms/d/e/1FAIpQLSdCkwwaS5KR7GzTe2b4FHzf5LPsk00zQCqGApISzcC4gqJTMg/viewform