Classes¶
User defined classes can be created using the class() constructor, see here. Usually classes are defined using a compound declaration.
class(Arg₁, Arg₂, ...)Creates a new class with additional properties based on the types of
Arg₁, Arg₂, ...:classAdds a parent class. Multiple parent classes are allowed.
methodAdds a field. Instances of this class will have space allocated for all fields, fields cannot be added or removed from instances later. Fields are accessed using the associated method.
Name is ValueNamed arguments add shared values to the class. If
Classis a class, thenClass::Namewill return the shared value called Name.
Certain shared values have special meaning. If c is a class, then:
The name
c::newis always set to a function equivalent to the following:1fun(Arg₁, Arg₂, ...) do 2 let Instance := new instance of c 3 c::init(Instance, Arg₁, Arg₂, ...) 4 ret Instance 5end
This cannot be overridden, if new is passed as a named argument to class(), it is ignored.
The value of
c::initis used as the initializer and should be a callable value (function, method, etc). This value is called byc::newto initialize a new instancecwith the given arguments.If init is not set, a default initializer is set which assigns positional arguments to the instance fields in order. Any named arguments are assigned to the corresponding field by name.
The value of
c::ofis used as the constructor and should be a callable value (function, method, etc). This value is called when the class is called as a function, i.e.c(...)is equivalent toc::of(...).If of is not set, a default constructor is set which simply calls
c::new.
Methods¶
Like all types in Minilang, classes can be used to define Methods.
Examples¶
1class: account(:Balance,
2 init is fun(Account, Balance) do
3 Account:Balance := Balance
4 end
5)
6
7meth :deposit(Account: account, Amount: real) do
8 Account:Balance := old + Amount
9end
10
11meth :withdraw(Account: account, Amount: real) do
12 Account:Balance := old - Amount
13end
14
15let Account := account(100)
16Account:deposit(200)
17Account:withdraw(150)
18print('Balance = {Account:Balance}\n')
Balance = 150