What is the difference between dynamic and Object in dart?

user3761898 picture user3761898 · Jul 7, 2015 · Viewed 18.5k times · Source

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

Answer

lrn picture lrn · Jul 8, 2015

Another perspective on dynamic is that it's not really a type - it's a way to turn off type checking and tell the static type system "trust me, I know what I'm doing". Writing dynamic o; declares a variable that isn't typed - it's instead marked as "not type-checked".

When you write Object o = something; you are telling the system that it can't assume anything about o except that it's an Object. You can call toString and hashCode because those methods are defined on Object, but if you try to do o.foo() you will get a warning - it can't see that you can do that, and so it warns you that your code is probably wrong.

If you write dynamic o = something you are telling the system to not assume anything, and to not check anything. If you write o.foo() then it will not warn you. You've told it that "anything related to o is OK! Trust me, I know what I'm doing", and so it thinks o.foo() is OK.

With great power comes great responsibility - if you disable type-checking for a variable, it falls back on you to make sure you don't do anything wrong.