Skip to content

Constants

2009 March 30
by Sven Busse

Juten Tach,
in the Adobe Livedocs, the description for the keyword const says:
“Specifies a constant, which is a variable that can be assigned a value only once.”
So why then does that not work:

const mySomething:String;
mySomething = "Test";

Grrrr ….

9 Responses leave one →
  1. hugo m. permalink
    March 30, 2009

    const mySomething:String = “Test”;
    you have to assign it right away :)

  2. jwopitz permalink
    March 30, 2009

    const are declared inline like so:
    const MY_SOMETHING:String = “test”;
    Trying to assign it elsewhere rather than where it is declared will through a Compile Time Error (CTE)

  3. March 30, 2009

    hi,
    yes, i know. That’s the point. It shouldn’t be that way.

  4. March 31, 2009

    Constant is not variable, it is value. During compile every occurence of const is converted to exact value, so it can’t be set during runtime

  5. March 31, 2009

    hi,
    yes, but it is explained differently in the documentation and in other languages, like Java for example, my little script would be possible.

  6. April 9, 2009

    Moin Sven,
    Java doesn’t have something like real constants. Just object properties with the final modifier, which means that a value may be assigned only once to the property. Your script would therefore not work in Java either.
    To my understanding the documentation is explaining it correctly, but you have to keep in mind that the declaration already assigns a value implicitly, usually null or 0. Thus your example would result in two assignments, one implict and one explicit.

  7. April 9, 2009

    hi,
    understood. I think, that final keyword for java was, what i wanted to say. Primitive variables are usually initialized with undefined in Actionscript. Objects with null. So at least, the documentation should say, that a constant has to be initialized with the desired value right away.

  8. Alex Schliebner permalink
    July 9, 2009

    I desagree with holger. In Java with a final class member Sven’s code would work. The initialization of a final member in Java happens at runtime. It _must_ be in line with its declaration _or_ inside the constructor. Further assignments to a final member or a missing initialization result in a compiler error.
    I agree with Sven, that the documentation is imprecise. You could understand it the way Sven did – similar to Java’s final modifier. But that’s not what it really is. A const looks to more like the C/C++ precompiler statement #define.

Trackbacks and Pingbacks

  1. AS3 – feature request filed – const initialization in constructor | Ghost23 Blog

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS

*