Open In App

Dart – Type System


The Dart programming language is considered type safe, meaning it ensures that the variable’s value always matches the variable’s static type through a combination of static type checking and runtime checking. It is also known as Sound Typing. It comes in handy while debugging the code at compile time.

All forms of static errors can be resolved by adding type annotations to generic classes.Some frequently used generic collection classes are listed below:

Example 1: The below code will throw an error on listwhen a call to the printInts(list) is made.

void printInts(List<int> x) => print(x);

void main() {
  var list = [];
  list.add(1000);
  list.add(2000);
  printInts(list);
}

Output:

error - The argument type 'List' can't be assigned to the parameter type 'List' at lib/strong_analysis.dart:27:17 - (argument_type_not_assignable)

The above error occurred due to an unsound implicit cast from a dynamic type List to an integer type , meaning declaring var List = [] doesn't provide sufficient information to the dart analyzer about the typing of the list items. To resolve this issue we pass the type annotation to the list variable as shown below:

// Using num data type in Dart
void printInts(List<int> a) => print(a);

void main() {
  var list = <int>[];
  list.add(1000);
  list.add(2000);
  printInts(list);
}

Output:

[1000, 2000] 

Concept of Soundness:

Soundness is the process of making sure that the code doesn't run into an invalid state. For instance, if a variable's static type is boolean, it is not possible to run into a state where the variable evaluates to a non-string value during runtime. 

Benefits of having Soundness:

Article Tags :