Classes

Creating a class

Defining the class

You can easily define a class using this simple syntax

class ClassName {
}

Adding fields

Fields are variables that can be accessed from any functions of the class, but also externally from other functions that have access to the specific classes instance.

Fields are defined using a simple name: type; assignment. You can not set a default value, unless you do it from the constructor.

class ClassName {
    a: i64;
    b: i64;
    text: *i8;
}

Adding methods

Methods are functions inside the class. All methods have access to an argument named this which is the specific instance of the class, that the method is being called on.

Methods are defined the same way as normal functions. There is no need to add the this argument manually.

class ClassName {
    a: i64;
    b: i64;
    text: *i8;
    
    func print() {
        printf("%s%d\n", this.text, this.a+this.b);
    }
}

Adding a constructor

A constructor is a special method that is called when the class is initialized. The method name has to be constructor.

A class doesn't have to have a constructor. When a new instance of a class is created, if it doesn't have a constructor, all fields will be initialized with null values.

class ClassName {
    a: i64;
    b: i64;
    text: *i8;
    
    func constructor(a: i64, b: i64, text: *i8) {
        this.a = a;
        this.b = b;
        this.text = text;
    }
    
    func print() {
        printf("%s%d\n", this.text, this.a+this.b);
    }
}

Using a class

Creating a new instance

To create a new instance of a class, simply use the new ClassName() expression, supplying any arguments necessary. You can store this new instance in a variable with the classes data type.

var instance: ClassName = new ClassName(1, 2, "Sum of 1 and 2: ");

Accessing fields

Any fields of a method can be externally accessed and both read and written to.

printf("%d\n", instance.a);
instance.a = 1;

Calling methods

Methods are called similairly as in other languages

instance.print();

Last updated