-
Notifications
You must be signed in to change notification settings - Fork 0
/
variance_test.dart
55 lines (47 loc) · 1.36 KB
/
variance_test.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import '_.dart';
import 'subtyping_test.dart';
bool isSupertype<T, U>() {
return (T _) {} is Function(U);
}
void main() {
test('all generics in dart are covariant', () {
final List<Object> a = <int>[1];
show(
<int>[] is List<Object>,
<Object>[] is List<int>,
a is List<int>,
);
});
test('which is not good', () {
final l = [1, 2, 3];
// variable assignment is possible only if `l2` is a subtype of `l`
// since List is covariant, we can legally generalize the type
final List<Object> l2 = l;
l2.add('oops');
});
test('contravariance exists only in function parameters', () {
show(
isSubtype<num, int>(),
isSubtype<num Function(), int Function()>(),
isSubtype<Function(num), Function(int)>(),
);
});
test(
'if a type is both covariant and contravariant, then it is invariant (due to antisymmetry)',
() {
show(
isSubtype<num Function(num), int Function(int)>(),
isSubtype<int Function(int), num Function(num)>(),
);
});
test('what if generic is a contravariant type?', () {
show(
isSubtype<List<Function(num)>, List<Function(int)>>(),
isSubtype<MapEntry<Function(num), int>, MapEntry<Function(int), num>>(),
);
});
test('isSupertype', () {
show(isSupertype<num, int>());
});
// there is NO way to make your generic contravariant
}