Home > database >  Dart: dynamic vs nullable Object
Dart: dynamic vs nullable Object

Time:01-09

Is there any difference between dynamic and Object? in dart?

This question may sound a duplicate of this What is the difference between dynamic and Object in dart?. However, I think it is not. I am not talking about semantic difference or any warnings thrown by the dart analyzer, or anything from a coder's perspective. I want to know is there a real difference between both under the hood.

I can assign any data value to both.

When I run the following:

Object? a;
dynamic b;
print(a.runtimeType);
print(b.runtimeType);

I get:

Null
Null

I know dynamic is a keyword, while Object? is a Object class. But does dynamic infer to Object?.

I'm new to Dart lang. So, please enlighten me.

CodePudding user response:

Yes, there is a difference.

The types dynamic and Object? are equivalent wrt. subtyping. Both are "top types" which means that every type is a subtype of them both, even each other. So, for subtyping there is no difference.

The difference is entirely in what you can do with an expression that has one of those types.

If an expression has type Object?, then the only methods you can call on it are the methods of Object and Null. The only types you can assign the expression to are top types.

If the expression has type dynamic, it is as if the static type system has been turned off. You are allowed to call any method (like dynamicExpression.arglebargle()) without any warning. If the method isn't there at runtime, it'll throw an error. And you can assign the value to any type. If the value turns out to not have that type at runtime, it'll throw an error. (This is usually called "implicit downcast" because it works as if an is ExpectedType was added to the expression by the compiler.) Also, because a dynamic expression is treated as having any method, you cannot call extension methods on it.

It's like dynamic is a type alias for Object? with the extra effect of turning off static type checking.

CodePudding user response:

When do you declare a variable as an Object?, during compile-time the compiler knows that type of the variable is Object? and it remains Object? forever. You can assign any type to this variable because every other type either extends the Object or null.

When do you declare a variable as a dynamic, during compile-time the compiler does not know the type of the variable and just ignores it. The compiler will check the type only during run-time and will infer the type according to the value you assigned.

CodePudding user response:

  • dynamic contains Exception. Object can only represent known data types and Null, (excluding Exception)
  • Related