Greetings, future Dart programmers! Are you prepared to delve deeper into Dart? Our upcoming adventure explores fundamental language constructs: Basic Data Types and Type Conversion. We'll examine the process of converting one type of data to another, a process akin to decrypting alien messages into human speech. We'll study both explicit and implicit conversions and learn to recognize potential pitfalls. So, let's supercharge our cognitive engines!
Dart, being a type-safe language, generally does not perform many implicit conversions to avoid unexpected behavior and maintain code clarity. However, Dart does allow some types to be used interchangeably in a context where it makes sense, without the need for explicit conversion. A common scenario involves numeric types and the num superclass.
For example, Dart implicitly allows the assignment of an int value to a variable of type num because num is a common superclass for both int and double types:
This works because num can hold either an integer or a double value, with Dart intelligently inferring the specific type based on the assigned value. However, for most other type conversions, Dart requires explicit action.
When it comes to converting types that are not implicitly interchangeable, like converting double to int or vice versa, Dart requires explicit conversion to ensure the programmer's intention is clear, safeguarding against potential data loss or precision issues. Here's how you can convert a double to an int explicitly, and vice versa:
Notice that converting a double to an int explicitly removes the fractional part. When casting an int to a double, the number becomes a floating-point, but its value essentially remains the same.
