Tuple constructors
Factor handbook > The language > Objects > Tuples

Prev:Slot accessors
Next:Tuple subclassing


Tuples are created by calling one of two constructor primitives:
new ( class -- tuple )

boa ( slots... class -- tuple )


A shortcut for defining BOA constructors:
C:


By convention, construction logic is encapsulated in a word named after the tuple class surrounded in angle brackets; for example, the constructor word for a point class might be named <point>.

Constructors play a part in enforcing the invariant that slot values must always match slot declarations. The new word fills in the tuple with initial values, and boa ensures that the values on the stack match the corresponding slot declarations. See Tuple slot declarations.

All tuple construction should be done through constructor words, and construction primitives should be encapsulated and never called outside of the vocabulary where the class is defined, because this encourages looser coupling. For example, a constructor word could be changed to use memoization instead of always constructing a new instance, or it could be changed to construct a different class, without breaking callers.

Examples of constructors:
TUPLE: color { red integer } { green integer } { blue integer } { alpha integer initial: 1 } ; ! The following two are equivalent C: <rgba> color : <rgba> color boa ; ! We can define constructors which call other constructors : <rgb> ( r g b -- color ) 1 <rgba> ; ! The following two are equivalent; note the initial value : <color> ( -- color ) color new ; : <color> ( -- color ) 0 0 0 1 <rgba> ; ! Run-time error "not a number" 2 3 4 color boa

Parameterized constructors