Prototypes
Object prototypes.
Type and Extends
#[type]
Point2D: {
float x: 0;
float y: 0;
#[constructor] // all of these will get called with "new"
fn is_a_point() {
self.isapoint = true;
}
fn length() -> float {
Num.sqrt(self.x.pow(2) + self.y.pow(2))
}
fn add(x: float, y: float) -> float {
x + y
}
}
#[type]
//#[extends(self.Point2D)] // works too
#[extends('Point2D')] // only one extends (single inheritance) for now
Point: {
float z: 0;
#[constructor] // optional, all are called with "new"
fn init() {
self.initialized = true;
}
fn length() -> float {
Num.sqrt(self.x.pow(2) + self.y.pow(2) + self.z.pow(2))
}
#[dropped] // optional, all called when "drop" (Std.drop(..) - see below)
fn dropped() {
super.point_dropped = true;
}
}
#[test]
fn point_2d() {
const point = new Point2D { x: 2, y: 2 };
assert_eq(point.length().round(2), 2.83);
assert_not(point.initialized);
assert(point.isapoint);
}
#[test]
fn point_3d() {
const point = new Point { x: 2, y: 2, z: 2 };
assert_eq(point.length().round(2), 3.46);
assert_eq(point.length<Point2D>().round(2), 2.83);
assert(point.initialized);
assert(point.isapoint);
assert_eq(typeof point, "obj");
assert_eq(typename point, "Point");
drop(point); // will remove the point from the graph and call all #[dropped]
assert(self.point_dropped);
}
#[test]
fn static_add() {
assert_eq(<Point2D>.add(12.5, 11.1), 23.6);
assert_eq(<Point>.add(14.4, 10), 24.4);
assert_eq(<self.Point2D>.add(25, 42), 67);
}Type Name Collisions
Type Names as Types
Last updated