Constructors



next up previous contents index
Next: Class Constructors Up: Expressions Previous: Identifiers that denote

Constructors

There are special forms called constructors that enable users to create and initialize "record", [tex2html_wrap2909]struct, "oneof", and "maybe" objects. A constructor has the form

<tagged_type_desig> "{" <field_inits> "}"
where
<field_inits> -> <field_init> ["," <field_init>]*
<field_init> -> <idn> := <expr>
The tagged_type_desig is the type of the constructed object. If a "struct" or "record" is being constructed, the component names in the field list must be exactly the field names in the tagged_type_desig, although the names may appear in any order in the constructor; the type of the initialization expression for a field must be a subtype of the declared type of that field. The expressions are evaluated in an unspecified order; the results form the components of the newly constructed object, which is the value of the constructor expression. For example,
rt = record[x: int, c: char]
x: rt := rt{c := 'A', x := 7}      % legal
x := rt{x := 7}                    % compile-time error -- not enough fields
x := rt{x := 7, d: 'A'}            % compile-time error -- misnamed field
If a "oneof" or "maybe" is being constructed, just one field name of the type can be present, and the type of the expression must be a subtype of the declared type of that field; the result is a new "oneof" or "maybe" object with the given tag whose value is the object resulting from evaluating the expression. For example,
ot = oneof[none: null, some: int]
x: ot := ot{none := nil}           % x's object has tag none and value nil
x := ot{some: 7}                   % now x's object has tag some and value 7
x := ot{some: 3.1}                 % compile-time error -- expression has wrong type
Decomposition of "oneof" objects is usually done via the tagcase statement (8.11).



theta-questions@lcs.mit.edu