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?
Dart numbers (the type num ) are either integers (type int ) or doubles (type double ). It is easy to check if a number is an int , just do value is int .
Dart – Read an Integer from Console To read an integer from console in Dart, first read a line from console using stdin. readLineSync() method, and then convert this line (string) into an integer using int. parse() method.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With