Classes¶
Classes can be used to define custom datatypes that bundle data and operations on this data.
Defining Classes¶
To define a class we use the following syntax:
- The keyword
class
. - The name of the class ("Lasso" in the following examples).
- To define the constructor of the class we list the parameters (inputs) necessary to create an instance. This list is enclosed in parentheses and separated by commas,
(regularizationStrength: Float)
in the following snippet. For each parameter, we list the name of the parameter followed by a colon and its type. - Finally, we have the body of the class, which lists the members (attributes for data and methods for operations on this data, as explained in the following sections) of the class enclosed by curly braces.
Defining Attributes¶
The data of a class is called attributes. We differentiate static attributes, which are available on the class itself, and instance attributes, which are available on instances on the class. Here is the syntax to define attributes:
- The modifier keyword
static
to define a static attribute (no modifier needed to define an instance attribute). - The keyword
attr
. - The name of the attribute ("regularizationStrength" in the following example).
- A colon followed by the type of the attribute ("Float" in the next example).
Defining Methods¶
Methods represent operations on the attributes of a class. As with attributes we differentiate static methods, which are accessible from the class itself, and instance methods, which are available on instances of the class. The syntax to define methods is as follows:
- The modifier keyword
static
to define a static method (no modifier needed to define an instance method). - The keyword
fun
. - The name of the attribute ("fit" in the following example).
- The list of parameters (inputs) enclosed in parentheses and separated by commas (
(features: Table, target: Table)
in the following snippet). For each parameter we list the name of the parameter followed by a colon and its type. - Optionally, we can list the results (outputs) after the symbol
->
. If this section is missing it means the method does not produce results. The list of results is again enclosed in parentheses and we use commas to separate the entries. If there is exactly one result we can omit the parentheses (see-> trainedModel: Lasso
in the following example). For each result we specify its name followed by a colon and its type.
class Lasso(regularizationStrength: Float) {
attr regularizationStrength: Float
fun fit(features: Table, target: Table) -> trainedModel: Lasso
}
Constructors¶
TODO
Subclassing¶
TODO
Using a Class as a Type¶
To express that the type of a declaration is some class we simply write the name of the class as the type. For example, we could declare a function that plots the line learned by a ridge regression model like this: