Chapter 2 - about checking type

  num someNumber = 3;
  if (someNumber is int) {

Hi, I find that the above code can be run successfully and print false in the console. What’s going on inside? If I remove the condition, the code even not compile.

I really don’t know why is that.

Another question is I cannot find a way programatically to know a number belongs to num or not.
For example:

num someNumber = 3;
print(someNumber is num);

The first print statement is always true no matter it is num, int or double.
The second print statement will print int, instead of num.

Any way to check a number belongs to num?

The next chapter (3) will cover this. The num type could be a double at runtime, so the static analysis/compiler will preemptively complain. When you enclose the statement in a conditional block with the is type test operator, to test for an int, the compiler can affirm .isEven function will be called on an int value

num is for numeric values whose types are not known at compile time. It can store a int or double

The num type is derived from Object
The int and double types are derived from num, so they all belong to it.

num someNumber = 3;
print(someNumber is Object); // True for all values in Dart
print(someNumber is num); // True
print(someNumber is int); // True
print(someNumber.runtimeType); // int

Thank you for this explanation as well as other explanations that you’ve been giving. I’m currently working on the second edition of the book so if you have suggestions for improvement, please let me know. I pay attention to these Q&A forums before publishing.


Thank you @suragch for your comment and for writing the Dart Apprentice book, which I have recently enjoyed reading through :open_book:

I look forward to seeing the second edition, and I will be sure to let you know if I identify any potential improvements in the meantime :+1:

1 Like

The book is an easy read. Although I has experience in Python programming, I still learn something in reading this book. Now, I have different view when I learn programming the first time. I will try to extract the concept that is essential to different programming language, which is not possible when I learn at the first time.

My opinion may be biased, may be you can put the small session in Chapter 3 about dynamic and Object? back into Chapter 2 about variable assignment.

Thank you for keep an eye in the forum. I believe as you see the questions in the forum, you will have an idea about how to prepare the second edition.

Hi @lauragales thank you for your answer. Although I already know some Python programming, there is still something that I felt not easy in Dart. My ultimate goal is to learn flutter development. Many courses teach Dart and Flutter together but I would like to have a foundation on Dart first. I believe building a foundation on Dart is essential first.

1 Like