Velo by Example: Extension Functions

Extension functions let you add methods to existing types without modifying them. The receiver is declared in parentheses after ext.

An extension function for int that returns the maximum of two integers.

ext(int a) max(int b) int {
    if (a > b) then a else b;
};

int maxValue = 5.max(10);  # 10

An extension for str that inserts a substring at a given position.

ext(str a) insert(int index, str s) str {
    a.sub(0, index).con(s).con(a.sub(index, a.len));
};

str result = "Hello".insert(5, " World");
# "Hello World"

Extensions without parameters — parentheses are optional when calling.

ext(bool b) str() str {
    if b then "true" else "false"
};

bool flag = true;
str s1 = flag.str();   # with parens
str s2 = flag.str;     # without parens

You can extend classes too.

ext(Terminal t) printInt(int a) str {
    t.println(a.str);
};

term.printInt(42);  # prints "42"