Methods
Methods in Spice basically are functions / procedures, assigned to a struct. Within methods,
fields of the parent struct can be accessed like this: this.fieldName.
Usage¶
A basic setup with one struct field, as well es a getter and a setter could look like this:
| Spice | |
|---|---|
Output:
| Text Only | |
|---|---|
Method visibility¶
Like functions and struct fields, methods are private by default. Mark a method public to allow code in other
source files to call it:
| Spice | |
|---|---|
A method that is not marked public can only be called from within the same source file.
Chaining method calls¶
Methods can be called on the result of any expression, not only on variables. This allows chaining calls:
The receiver of a method call can be the result of a call, a subscript (counters[1].get()), a parenthesized expression
((*counterPtr).get()) or an error propagation (getCounter()!.get()). Pointers and references are dereferenced
automatically. A temporary receiver, like the Counter that makeCounter() returns, is destructed like any other
temporary value.
In the same way, a function or procedure, that an expression evaluates to, can be called directly. A function or procedure, that is stored in a struct field, can be called like a method:
| Spice | |
|---|---|
If the struct has a method with the same name, that matches the arguments, the method is called instead of the field. To
call the field in this case, wrap the field access in parentheses: (button.onClick)().
Methods on generic structs¶
Methods on a generic struct automatically inherit the struct's type parameters — you do not repeat the parameter list on the method:
| Spice | |
|---|---|
When Stack<int> is instantiated, push accepts an int and pop returns an int.
Tip
You can initialize or destroy structs by using constructors and destructors. Read more about those in the respective documentation section.