Constants
2009 March 30
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 →

const mySomething:String = “Test”;
you have to assign it right away
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)
hi,
yes, i know. That’s the point. It shouldn’t be that way.
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
hi,
yes, but it is explained differently in the documentation and in other languages, like Java for example, my little script would be possible.
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.
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.
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.