0

What is the point of specifying variables at all in dart instead of just using var and dynamic?

I am new to dart and would like to know for future projects.

  • How do you see "specifying variables" different from using `var` (or `dynamic`) ? – Luuk Mar 12 '23 at 14:54
  • Maintainability and typesafety for instance. `var a; a = 3; a = 'foo';` or `dynamic b = 5; b = 'bar';` are completely legal in dart. Then try to determine, which type `a` or `b` are without reading all of your code ... And if you can't, neither can the compiler ... – derpirscher Mar 12 '23 at 14:54
  • 1. [`var` is not the same as `dynamic`](https://stackoverflow.com/a/75714741/). 2. Whether you [choose to use inferred types or explicit types](https://stackoverflow.com/q/64260613/) is a stylistic choice. 3. Using *static* typing instead of using `dynamic` primarily shifts *when* errors are reported. (For example, calling a function with the wrong arguments, making a typo in a method name.) Discovering mistakes earlier is better than later. Additionally, using static typing allows the compiler to generate faster and leaner code by not needing to generate runtime checks. – jamesdlin Mar 12 '23 at 18:03

1 Answers1

0

There are several reasons why one would do such a thing.

Type loosening

Sometimes, you want a variable to be of a more permissive type than inference gives you.

For example, the following snippet won't compile as-is, because score is an int:

var score = 0;
score += 0.5;

Instead, score must be explicitly defined as a num value:

num score = 0;
score += 0.5;

This also applies for nullable values.

// var score = 0; // Won't compile
int? score = 0;   // This works
score = null;

Type tightening

Conversely, sometimes type inference is not specific enough.

Consider the following example:

const myList = [];

What types can myList hold? In this case, the literal [] creates an empty list of type dynamic. This can be restricted in two separate ways.

const myList = <int>[]; // LHS type inference
const List<int> myList = []; // RHS type inference

API documentation

It's often beneficial to use type annotations on public API elements, as detailed in the Effective Dart: Design guidelines and type_annotate_public_apis linter rule.

hacker1024
  • 3,186
  • 1
  • 11
  • 31