Product SiteDocumentation Site

3.3. ::CONSTANT

The ::CONSTANT directive creates methods that return constant values for a class and its instances.

>>-::CONSTANT--name--value-------------------------------------------><

A ::CONSTANT directive defines a method that returns a constant value. This is useful for creating named constants associated with a class.
The name is a literal string or a symbol that is taken as a constant. A method of the given name is created as both an instance method and a class method of the most recent ::CLASS directive. A ::CLASS directive is not required before a ::CONSTANT directive. If no ::CLASS directive precedes ::CONSTANT, a single constant method method is created that is not associated with a class but is accessible to the main (executable) part of a program through the .METHODS built-in object. Only one ::CONSTANT directive can appear for any method name not associated with a class. See Section 6.14, “The METHODS Directory (.METHODS)” for more details.
The methods created by a ::CONSTANT directive are UNGUARDED and will have a return result that is specified by value. The constant value must be a single literal string or symbol that is taken as a constant. Also permitted is the single character "-" or "+" followed by a literal string or symbol that is a valid number. Here are some examples of valid constants:

Example 3.6. CONSTANT examples

::class MathConstants public
::constant pi 3.1415926
::constant author "Isaac Asimov"
::constant absolute_zero -273.15

A ::CONSTANT directive is a shorthand syntax for creating constants associated with a class. The created name constant can be accessed using either the class object or an instance of the class itself.

Example 3.7. CONSTANT access examples

say "Pi is" .MathConstants~pi    -- displays "Pi is 3.1415926"
instance = .MathConstants~new
say "Pi is" instance~pi          -- also displays "Pi is 3.1415926"

::class MathConstants public
::constant pi 3.1415926