Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use num in Dart

Tags:

dart

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?

like image 747
Michel Feinstein Avatar asked Nov 27 '18 20:11

Michel Feinstein


People also ask

How do you know if a Dart number is int?

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 .

How do you read Dart numbers?

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.


1 Answers

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

like image 52
Saed Nabil Avatar answered Nov 16 '22 01:11

Saed Nabil