Using generics vs returning dynamic in Dart
I think this is a good question, the main difference between generics and dynamic
to me is:
Generics are restricted to only 1 type, while dynamic is not because it stops the compiler to perform "type checking".
Real example:
class Foo<T> { var bar = List<T>(); var foo = List<dynamic>(); void addBar(T elem) { bar.add(elem); } void addFoo(dynamic elem) { foo.add(elem); }}var bar = Foo<String>() ..addBar("hello") ..addBar(123); //compile error, you can't add an integer to <string> listvar foo = Foo<String>() ..addFoo("hello") ..addFoo(123); //OK because dynamic accept any type
Dynamics enable you to use mixed maps Map<String, dynamic>
or "emulate" union types logic like:
dynamic foo = //some type;if (foo is bool) { //do somethings} else if (foo is String) { //do something else}
without using interfaces or inheritance for types.
So the next question should be, what is the difference between Object
and dynamic
?
You can find the answer here: https://stackoverflow.com/a/31264980/2910520