Open In App

Dart – Type System

Last Updated : 03 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report


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:

  • List
  • Map

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

Dart
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:

Dart
// 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:

  • Debug type related bugs at compile time.
  • Makes code easier to read and debug.
  • Get alters when changing code pieces that breaks other dependent part of the code.
  • One of its key features is Ahead Of Time (AOT) compilation, which significantly reduces the compile time of the code and increases efficiency. 
     

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads