Why does Dart have compile time constants?

前端 未结 2 1065
野的像风
野的像风 2021-01-02 00:10

Dart has the concept of compile-time constants. A compile-time constant is parsed and created at compile time, and canonicalized.

For example, here is a const<

相关标签:
2条回答
  • 2021-01-02 00:16

    From the mailing list, Florian Loitsch writes:

    The canonicalization property of compile-time constants is nice, but not the main-reason to have them. The real benefit of compile-time constants is, that they don't allow arbitrary execution at construction and can therefore be used at places where we don't want code to executed. Static variables initializers, for example, were initially restricted to compile-time constants to avoid execution at the top-level. In short, they make sure that a program starts with 'main' and not somewhere else.

    0 讨论(0)
  • 2021-01-02 00:25

    Lasse's answer here helped me a lot

    So, what are compile-time constants good for anyway?

    • They are useful for enums.
    • You can use compile-time constant values in switch cases.
    • They are used as annotations.

    Compile-time constants used to be more important before Dart switched to lazily initializing variables. Before that, you could only declare an initialized global variable like "var x = foo;" if "foo" was a compile-time constant. Without that requrirement, most programs can be written without using any const objects

    0 讨论(0)
提交回复
热议问题