If I have a function that returns a value of an unknown type, do I use dynamic
, representing any object, or Object
, which is the ancestor of all other types?
The style guide discusses this question for parameters, but not for return values.
How should I annotate the return value and why?
The function's return type is string. The function returns a string value to the caller. This is achieved by the return statement. The function test() returns a string.
dynamic is a dynamic type that accepts any type of value and disables type checking The object is a type that accepts any non-nullable types.
You can use normal global variables in Dart like explained in Global Variables in Dart. final Map<String,int> myGlobals = <String,int>{}; to create a map that stores integer values with string names. Set values with myGlobals['someName'] = 123; and read them with print(myGlobals['someName']); .
Dart dynamic type In Dart, when a variable is declared as a dynamic type, it can store any value, such as int and float . The value of a dynamic variable can change over time within the program.
Dart engineer Bob Nystrom writes:
Return types are an interesting twist on this problem. With parameter types, the guidelines are pretty straightforward:
If you use Object
as a parameter type, you're saying "my method will safely accept any object and only use it for stuff like toString()
that all objects support".
If you use dynamic
(or nothing) as a parameter type, you're saying "Dart's type system can't easily express the type that I accept here" or "I didn't bother to annotate".
It's tricky to flip (1) around. For a return type, I guess Object
would say "You better not call anything except toString()
or other stuff all objects support before doing a type test yourself", where dynamic
would I think mean "we can't easily annotate this so you and I better just know what we're doing".
The user would have to "cast" it to a specific type that they expect to see to avoid compiler warning and get an error earlier in checked mode.
For what it's worth, in many cases you wouldn't have to cast even if you return Object. Dart allows implicit downcasting when you initialize a local variable with a type annotation. So you can do:
Object foo() => 123;
main() {
int x = foo(); // Implicit downcast. No type warning.
}
I think in this case, I would probably do dynamic
, though. I think that conveys "I don't know what type this returns, but you should" better than Object
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With