# Interface und Sammlung von Vergleichsmethoden
role Comparable {
# spätere Implementierung erzwingen
method compare { ... }
method less_than ($other) {
$.compare($other) == -1
}
method equal_to ($other) {
$.compare($other) == 0
}
method greater_than ($other) {
$.compare($other) == 1
}
}
# Ein Interface ohne Default-Implementierung
role Printable {
# spätere Implementierung erzwingen
method to_string { ... }
}
# Eine Währungs-Klasse,
class US::Currency {
# Methoden aus obenstehenden Roles einmischen
does Comparable;
does Printable;
# numerisches Attribut mit
# Schreibrechten und Defaultwert
has Num $.amount is rw = 0;
method compare ($other) {
$.amount <=> $other.amount;
}
method to_string {
sprintf '$%0.2f USD', $.amount;
}
}
# --- main ---
# Instanziierung
my $income = US::Currency.new(amount => 9876.50);
my $cost = US::Currency.new(amount => 1000 );
# Verwendung
say $income.to_string; # $9876.50 USD
say $income.perl; # Objekt-Dump
say $income.greater_than( $cost ); # true
# Introspection / Metamethods, siehe S12
say $income.HOW.perl; # metaclass object
say $income.WHAT.perl; # ähnelt Perl 5 'ref'
say $income.isa( 'US::Currency' ); # true
say $income.isa( 'EU::Currency' ); # false
Perl 6 kennt Rollen und viele andere Konzepte der Objektorientierung.
Dieser Text ist der Zeitschriften-Ausgabe 08/2007 von iX entnommen.
iOS, Android, Windows Phone 7 und HTML5 - das neue Sonderheft von heise Developer führt Einsteiger und Profis in die Programmierung mobiler Geräte ein.