Course of Raku / Objects, I/O, and exceptions / Classes and objects / Roles / Exercises / A dancing robot
Solution: A dancing robot
Here is a possible solution to the task.
Code
role Dancing {
method dance {
'spinning around';
}
}
class Robot {
method speak {
'beep';
}
}
my $plain = Robot.new;
my $dancing = Robot.new but Dancing;
say $plain.speak;
say $dancing.speak;
say $dancing.dance;🦋 You can find the source code in the file dancing-robot.raku.
Output
beep
beep
spinning aroundComments
Unlike the earlier examples,
Dancingdoes not replace an existing method — it brings a brand-newdancemethod thatRobotknows nothing about.Robot.new but Dancingmixes the role into a single object at run time, so$dancingcan bothspeak(from the class) anddance(from the role). The plain$plainonly ever learntspeak.The extra ability belongs to that one object, not to the
Robotclass. Calling$plain.dancewould be an error, because$plainnever received the role.