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: 9

Comments

  1. The role declares area as a stub ({ ... }), so any class that does the role must supply its own area. This guarantees every shape can report an area.

  2. $shape.^name asks the object for its class name, so the same loop labels each result correctly without knowing the type in advance.

Course navigation

Shapes sharing a role   |   Which quadrant