Dart symbol literals

十年热恋 提交于 2020-12-26 12:05:36

问题


I was reading this document on Zones and it has the following code:

runZoned(() {
  print(Zone.current[#key]);
}, zoneValues: { #key: 499 });

I tried to find more docs symbol literals, but I couldn't, they are very scarce.

I typed this code for a test:

var a = #b;

And I can see that a is a Symbol.

How does a Symbol literal work?

What does it reference to?

Just by creating one I create a new unique Symbol?


回答1:


Symbols are not unique. They are intended to represent source names at runtime, so the symbol value of the symbol literal #a (which can also be written const Symbol("a")) represents the identifier a.

Symbols occur only in the more dynamic parts of Dart. In particular they are used in the representation of named arguments used by the Invocation class (the argument passed to noSuchMethod) and the Function.apply function. If your platform has access to dart:mirrors, they are also used there, and that was the original use they were introduced for.

You shouldn't need to use symbols outside of those cases, but in some situations, like the #key above, it's just an easy way to provide a reproducible (not unique) token that carries its own name. Or, if you want a token that is unique to your own library, you can make a symbol for a private name, #_foo. This represents the library-private _foo identifier, which no other library can reproduce.

Having a representation of source names that is not a string allows, e.g., a Dart to JavaScript compiler to minify the names and not have to retain the longer source identifiers in the deployed code.



来源:https://stackoverflow.com/questions/59185676/dart-symbol-literals

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!