I am new to Dart and I can see Dart has num
which is the superclass of int
and double
(and only those two, since it's a compile time error to subclass num
to anything else).
So far I can't see any benefits of using num
instead of int
or double
, are there any cases where num
is better or even recommended? Or is it just to avoid thinking about the type of the number so the compiler will decide if the number is an int
or a double
for us?
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