Menu
Coddy logo textTech

Type Inference with 'var'

Part of the Fundamentals section of Coddy's Dart journey — lesson 10 of 94.

In Dart, var enables type inference, where Dart automatically determines variable types from assigned values.

void main() {
  var name = 'Dart Programmer';
  print(name);
}

Dart infers name as String. It works with other types too:

void main() {
  var age = 25;              // Inferred as int
  var price = 19.99;         // Inferred as double
  var isAvailable = true;    // Inferred as bool
  
  print(age);          // Outputs: 25
  print(price);        // Outputs: 19.99
  print(isAvailable);  // Outputs: true
}
challenge icon

Challenge

Beginner

Create a Dart program that demonstrates type inference with the var keyword:

  1. Declare a variable named name using var and assign it the string value "Dart"
  2. Declare a variable named year using var and assign it the integer value 2011
  3. Declare a variable named version using var and assign it the double value 2.19
  4. Declare a variable named isStronglyTyped using var and assign it the boolean value true
  5. Print each variable with a descriptive label in the following format:
Language: Dart
Created in: 2011
Current version: 2.19
Is strongly typed: true

Your output must match this exact format.

Cheat sheet

Use var for type inference - Dart automatically determines variable types from assigned values:

var name = 'Dart Programmer';  // Inferred as String
var age = 25;                   // Inferred as int
var price = 19.99;              // Inferred as double
var isAvailable = true;         // Inferred as bool

Try it yourself

void main() {
  // Declare your variables using var
  var name = ?;
  var year = ?;
  var version = ?;
  var isStronglyTyped = ?;
  
  // Print the variables with labels
  print("Language: " + name);
  print("Created in: " + year.toString());
  print("Current version: " + version.toString());
  print("Is strongly typed: " + isStronglyTyped.toString());
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals