Anonymous
Anonymous

Reputation: 357

Dart: dynamic vs nullable Object

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.

Upvotes: 0

Views: 372

Answers (3)

Kasymbek R. Tashbaev
Kasymbek R. Tashbaev

Reputation: 1473

When 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 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.

Upvotes: 1

lrn
lrn

Reputation: 71773

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.

Upvotes: 5

bakboem
bakboem

Reputation: 572

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

Upvotes: -2

Related Questions