Skip to content

Latest commit

 

History

History
62 lines (45 loc) · 2.3 KB

10.-constructors.md

File metadata and controls

62 lines (45 loc) · 2.3 KB

10. Constructors

  • A constructor is a special function that creates an instance of the class that it's associated with.
  • It can be used to set initial values for the new object.

Defining a constructor for a class: You can add a constructor for a class by adding the <constructor> specifier on the function name. Instead of specifying a return type on the function, the function is assigned the class name followed by any initialization of fields. A class can have more than one constructor.

{% code title="Verse Example 10.1" %}

class1 := class:
    Property1 : int
 
MakeClass1<constructor>(Arg1:int) := class1:
    Property1 := Arg1
 
Main():void =
    X := MakeClass1(1)
    F := MakeClass1()
    Z := F(2)

{% endcode %}

Adding variables and executing code in the constructor:

  • You can execute expressions within a constructor with the block expression, and introduce new variables with the keyword let.

{% code title="Verse Example 10.2" %}

MakeOtherClass1<constructor>(Arg1 : int) := class1:
    let:
        OnePlusArg1 := Arg1 + 1
 
    block:
        DoSomething(OnePlusArg1)
 
    Property1 := OnePlusArg1
 
    block:
        DoOtherStuff()

{% endcode %}

Calling other constructors in a constructor:

  • You can call other constructors from a constructor. You can also call constructors for the superclass of the class from a constructor of the class as long as all fields are initialized. When a constructor calls another constructor and both constructors initialize fields, only the values provided to the first constructor are used for the fields. The order of evaluation for expressions between the two constructors will be in the order the expressions are written (as far as side effects are concerned), but only the values provided to the first constructor are used.

{% code title="Verse Example 10.3" %}

MakeClass1Plus1<constructor>(Arg1 : int) := class1:
    MakeClass1<constructor>(Arg1 + 1) # Note use of <constructor> on invocation
 
# The base type constructor can be invoked in any order with respect to properties,
# but the properties "win"
MakeOtherClass2<constructor>(Arg1 : int, Arg2 : int) := class2:
    Property2 := Arg2
    MakeClass1<constructor>(Arg1)
    # Note that effects are still ordered as they appear in the code

{% endcode %}