When to use num in Dart
One benefit for example before Dart 2.1 :
suppose you need to define a double var like,
double x ;
if you define your x to be a double, when you assign it to its value, you have to specify it say for example 9.876.
x = 9.876;
so far so good.
Now you need to assign it a value like say 9
you can't code it like this
x = 9; //this will be error before dart 2.1
so you need to code it like
x = 9.0;
but if you define x as num
you can use
x = 9.0;
and
x = 9;
so it is a convenient way to avoid these type mismatch errors between integer and double types in dart.
both will be valid.
this was a situation before Dart 2.1 but still can help explain the concept
check this may be related
Not sure if this is useful to anyone, but I just ran into a case where I needed num
in a way.
I defined a utility function like this:
T maximumByOrNull<T, K extends Comparable<K>>(Iterable<T> it, K key(T),) {
return it.isEmpty
? null
: it.reduce((a, b) => key(a).compareTo(key(b)) > 0 ? a : b);
}
And invoking it like this…
eldest = maximumByOrNull(students, (s) => s.age);
… caused trouble when age
is an int
, because int
itself does not implement Comparable<int>
.
So Dart cannot infer the type K
in the invocation to maximumByOrNull
.
However, num
does implement Comparable<num>
. And if I specified:
eldest = maximumByOrNull(students, (s) => s.age as num); // this
eldest = maximumByOrNull<Student, num>(students, (s) => s.age); // or this
the complaint went away.
Bottom line: it seems num
implements Comparable
when int
and double
do not, themselves, and sometimes this causes trouble for generic functions.