Course of Raku / Addendum 🆕 / Types and text machines / Objects and classes / Exercises / Shapes sharing a role
Solution: Shapes sharing a role
Here is a possible solution to the task.
Code
role Shape {
method area { ... }
}
class Circle does Shape {
has $.radius;
method area { 3.14159 * $.radius ** 2 }
}
class Square does Shape {
has $.side;
method area { $.side ** 2 }
}
for Circle.new(radius => 2), Square.new(side => 3) -> $shape {
say "{$shape.^name}: {$shape.area}";
}🦋 You can find the source code in the file shapes-role.raku.
Output
Circle: 12.56636
Square: 9Comments
The role declares
areaas a stub ({ ... }), so any class that does the role must supply its ownarea. This guarantees every shape can report an area.$shape.^nameasks the object for its class name, so the same loop labels each result correctly without knowing the type in advance.