Search code examples
objectdartdynamictype

What is the difference between dynamic and Object in dart?


They both seem like they can be used in identical cases. Is there a different representation or different subtleties in type checking, etc?


Solution

  • The section Type dynamic from the Dart Programming Language Specification, 3rd Edition states :

    Type dynamic has methods for every possible identifier and arity, with every possible combination of named parameters. These methods all have dynamic as their return type, and their formal parameters all have type dynamic. Type dynamic has properties for every possible identifier. These properties all have type dynamic.

    That means you will not get warnings by calling any method on a dynamic typed variable. That will not be the case with a variable typed as Object. For instance:

    dynamic a;
    Object b;
    
    main() {
      a = "";
      b = "";
      printLengths();
    }
    
    printLengths() {
      // no warning
      print(a.length);
    
      // warning:
      // The getter 'length' is not defined for the class 'Object'
      print(b.length);
    }
    

    At runtime, I think, you shouldn't see any difference.