Product Site

3.4. ::CONSTANT

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

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 "floating" constant method is created that is not associated with a class but is accessible through the .METHODS built-in object. Only one ::CONSTANT directive can appear for any method name not associated with a class.

The methods created by a ::CONSTANT directive are UNGUARDED and will have a return result that is specified by value. If specified, the constant value must be a single literal string, a symbol that is taken as a constant, or an expression enclosed in parentheses. Also permitted is the single character "-" or "+" followed by a symbol that is a valid number. If value is omitted, the constant name will return its value in uppercase.

Here are some examples of valid constants:
Example 3.8. CONSTANT examples
::class MathConstants public
::constant pi 3.14159265
::constant author "Isaac Asimov"
::constant absolute_zero -273.15
::constant e ( rxcalcexp(1) )
::constant eSquare (self~e ** 2)
::constant primes (2, 3, 5, 7, 11, 13)

::class Search
::constant caseless

::requires rxmath library

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.9. CONSTANT access examples
say "Pi is" .MathConstants~pi    -- displays "Pi is 3.14159265"
instance = .MathConstants~new
say "Pi is" instance~pi          -- also displays "Pi is 3.14159265"

say .Search~caseless             -- "CASELESS"

::class MathConstants public
::constant pi 3.14159265

::class Search
::constant caseless

Notes:
  1. Calculated ::CONSTANT directives (where value is an expression enclosed in parentheses) can reference any other constant ::CONSTANT directives (where value is omitted, a single literal string, a symbol that is taken as a constant, or a valid number optionally preceded by "-" or "+"). For a calculated ::CONSTANT directive to reference another calculated ::CONSTANT directive, the referenced directive must be defined earlier in order of appearance. Forward references to calculated ::CONSTANT directives are not allowed.
  2. For a floating ::CONSTANT directive the constant value must be a single literal string, or a symbol that is taken as a constant, or a valid number optionally preceded by "-" or "+". An expression enclosed in parentheses is not allowed.
  3. A ::CONSTANT directive cannot have a method body.