role Associative

Object that supports looking up values by key

role Associative[::TValue = Mu, ::TKey = Str(Any)] { }

A common role for types that support name-based lookup through postcircumfix:<{ }>, for example Hash and Map. It is used for type checks in operators that expect to find specific methods to call. See Subscripts for details.

The % sigil restricts variables to objects that do Associative, so you will have to mix in that role if you want to use it for your classes.

class Whatever {};
my %whatever := Whatever.new;
# OUTPUT: «(exit code 1) Type check failed in binding; expected Associative but got Whatever 

Please note that we are using binding := here, since by default % assignments expect a Hash in the right-hand side. However, with the Associative role:

class Whatever is Associative {};
my %whatever := Whatever.new;

will be syntactically correct.

Methods

of

Defined as:

method of()

Associative is actually a parametrized role which can use different classes for keys and values. As seen above, by default it coerces to Str for the key and uses a very generic Mu for value.

my %any-hash;
say %any-hash.of;#  OUTPUT: «(Mu)␤» 

The value is the first parameter you use when instantiating Associative with particular classes:

class DateHash is Hash does Associative[Cool,DateTime{};
my %date-hash := DateHash.new;
say %date-hash.of# OUTPUT: «(Cool)␤» 

keyof

Defined as:

method keyof()

Returns the parametrized key used for the Associative role, which is Any coerced to Str by default. This is the class used as second parameter when you use the parametrized version of Associative.

my %any-hash;
%any-hash.keyof#OUTPUT: «(Str(Any))␤» 

Type Graph

Type relations for Associative
perl6-type-graph Associative Associative Mu Mu Any Any Any->Mu Pair Pair Pair->Associative Pair->Any QuantHash QuantHash QuantHash->Associative Cool Cool Cool->Any Iterable Iterable Map Map Map->Associative Map->Cool Map->Iterable PseudoStash PseudoStash PseudoStash->Map Hash Hash Hash->Map Setty Setty Setty->QuantHash Baggy Baggy Baggy->QuantHash Stash Stash Stash->Hash Set Set Set->Any Set->Setty SetHash SetHash SetHash->Any SetHash->Setty Mixy Mixy Mixy->Baggy Bag Bag Bag->Any Bag->Baggy BagHash BagHash BagHash->Any BagHash->Baggy Mix Mix Mix->Any Mix->Mixy MixHash MixHash MixHash->Any MixHash->Mixy

Stand-alone image: vector