Skip to content
Related Articles

Related Articles

Improve Article
Dart – Type System
  • Last Updated : 22 Dec, 2020

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 picese that breaks other dependent part of the code.
  • One of its key feature is Ahead Of Time (AOT) comilation, which significiantly reduces the comile time of the code and increases efficiency.



My Personal Notes arrow_drop_up
Recommended Articles
Page :