Search code examples
objectrakucalling-convention

How to get the `< ... >` syntax on an object?


In Raku: when I create an object with a CALL-ME method, I would like to use the < ... > syntax for the signature instead of ( '...' ) when ... is a Str. In the documentation, there is an example of creating an operator, which is an ordinary Raku sub with a special syntax. This sort of sub automatically converts < ... > into a Str. For example, if I have

use v6.d;
class A {
   has %.x;
   method CALL-ME( Str:D $key ) { say %!x{ $key } }
}

my A $q .= new( :x( <one two three> Z=> 1..* ) );
$q('two');
$q<two>;

But this produces

2
Type A does not support associative indexing.
  in block <unit> at test.raku line 10

Solution

  • An answer based on @raiph's comment:

    You need to implement the AT-KEY method on your type.

    You can do so directly like this:

    class A {
       has %.x;
       method CALL-ME( Str:D $key ) { say %!x{ $key } }
       method AT-KEY($key) { self.($key) }
    }
    

    Or you can do so by delegating AT-KEY to %!x using the handles trait:

    class A {
       has %.x handles <AT-KEY>;
       method CALL-ME( Str:D $key ) { say %!x{ $key } }
    }