I stumbled across the following code snippet in a Flutter package:
zoneValues: <dynamic, dynamic>{#goldentoolkit.config: config},
They are using a hash (#) in Dart code. I have never seen this before and did not know it existed.
When I tested using it in my IDE:
#anyword;
The analyzer does not give me any warnings for it.
print(#test);
This will print Symbol("test")
, meaning that it is the syntax for creating symbols, however, what does it do?
The Dart 2.2 language specification says:
One may well ask what is the motivation for introducing literal symbols? In some languages, symbols are canonicalized whereas strings are not. However literal strings are already canonicalized in Dart. Symbols are slightly easier to type compared to strings and their use can become strangely addictive, but this is not nearly sufficient justification for adding a literal form to the language. The primary motivation is related to the use of reflection and a web specific practice known as minification.
Minification compresses identifiers consistently throughout a program in order to reduce download size. This practice poses difficulties for reflective programs that refer to program declarations via strings. A string will refer to an identifier in the source, but the identifier will no longer be used in the minified code, and reflective code using these would fail. Therefore, Dart reflection uses symbols objects of type
Symbol
rather than strings. Instances ofSymbol
are guaranteed to be stable with respect to minification. Providing a literal form for symbols makes reflective code easier to read and write. The fact that symbols are easy to type and can often act as convenient substitutes for enums are secondary benefits.
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