4 ms·
I can't say, but I love what Perl 6 has done. For example, here's a Point class, with read/write, mandatory attributes: class Point { has $.x is rw
by Ovid 11y ago
I can't say, but I love what Perl 6 has done. For example, here's a Point class, with read/write, mandatory attributes:
class Point {
has $.x is rw is required;
has $.y is rw is required;
}
Like many dynamic languages, there's nothing to stop you from assigning the string "foo" to one of those attributes, so let's fix that, but go even further and constrain the X and Y coordinates from -10.0 to 10.0. (Note that a "Rat" is a rational number, so it's perfectly precise and doesn't suffer from floating points imprecision):
class Point {
subset PointLimit of Rat where -10.0 .. 10.0;
has PointLimit $.x is rw is required;
has PointLimit $.y is rw is required;
}
So what that's done is allowed the dev to declare a new type, PointLimit, on the fly. It must be a number from -10 to 10. And then we have our X and Y attributes:
my $point = Point.new( x => -1.2, y => 7.3 );
$point.x = 3.14;
$point.y = -22.0; # Boom! Constraint violation