Type inference
- Dart course
- Beginner
- Lesson 16/116
- 5 min
Learn var and type inference.
Type inference
Type inference means Dart automatically determines a variable's type from the value on the right. It works with the var keyword.
For example var age = 25; makes Dart infer age is an int. var price = 9.99; is a double, var name = 'Alex'; is a String.
This speeds up writing code. But once the type is set, it cannot change: var x = 5; followed by x = 'text'; is an error.
Practice Three types with var
Inside void main() declare var age = 25, var price = 9.99 and var name = 'Alex'. Print all three with print.
Starter code
// Declare variables with varSample solution
void main() {
var age = 25;
var price = 9.99;
var name = 'Alex';
print(age);
print(price);
print(name);
}Expected output
25 9.99 Alex
Limits of inference
Type inference is powerful but does not fit every case. For example in function parameters and class fields, writing the explicit type is common; it improves readability.
Also null cannot be the initial value: var x = null; makes Dart unable to infer and it assumes dynamic. This is undesirable; using a nullable type is better.
Tip: if the type is clearly known, write it; if unclear, use var. Restraint is always good.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When you write var x = 3.14;, what is the type of x?
var x = 3.14;- int
- dynamic
- double Correct answer
- object
Explanation: 3.14 is decimal so x becomes a double.
2 Inference keyword
____ name = 'Alex';
var name = 'Alex';
Explanation: var triggers type inference.
3 Inference concepts
| Term | Meaning |
|---|---|
var |
Inference |
int |
Integer |
double |
Floating-point |
String |
Text |