Velo by Example: Classes

Classes in Velo have constructor parameters, fields, and methods. Fields are read-only from outside the class.

A class is defined with class, constructor parameters in parentheses, and a body with fields and methods.

class Point(int x, int y) {
    int xCoord = x;
    int yCoord = y;

    func move(int dx, int dy) void {
        xCoord = xCoord + dx;
        yCoord = yCoord + dy;
    };
};

Create instances with new. Access fields (read-only from outside) and call methods.

Point p = new Point(10, 20);
int x = p.xCoord;       # reading: OK
# p.xCoord = 15;        # ERROR: read-only
p.move(5, 5);            # modify via method: OK

The class body acts as a constructor. Fields can be computed from parameters.

class Counter() {
    int value = 0;

    func increment() void {
        value = value + 1;
    };

    func getValue() int {
        value;
    };
};

Counter c = new Counter();
c.increment();
c.increment();
int v = c.getValue();    # 2

Classes can be nested inside other classes.

class LinkedList() {
    class Item(Item prev, any value) {};

    Item start;
    Item end;
    int length = 0;

    func add(any value) void {
        end = new Item(end, value);
        if (length == 0) {
            start = end;
        };
        length = length + 1;
    };
};