Topic Overview

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!

Implicit Conversions

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:

Dart
num n = 10;  // Implicitly, an integer is also a num.
print("The value of n: $n");  // Output: The value of n: 10

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.

Explicit Conversions

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:

double d = 10.25; // a double value
int i = d.toInt();  // explicitly casting the double to int
print("The value of i: $i");  // Output: The value of i: 10

int j = 100; // an integer
double e = j.toDouble(); // explicitly converting int to double
print("The value of e: $e"); // Output: The value of e: 100.0

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.

Converting to and from Strings
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal