How to check if a method is installed in the Perl 6 class?

I often want to check that I defined a method in a specific class. This caused a lot of problems when I renamed a method or otherwise rebuilt things in the architecture.

I know what I can use .^lookup, but it still seems strange to me that I will end up with a situation where it returns things in a different order than I expect (now ignore the signatures). Here is what I came up with:

use Test;

class Foo is Str {}
class Bar is Str { method Str { 'Hello' } }

can-ok Str, 'Str';
can-ok Foo, 'Str';
can-ok Bar, 'Str';

is Foo.^lookup( 'Str' ).package.^name, 'Foo', 'Foo defines Str';
is Bar.^lookup( 'Str' ).package.^name, 'Bar', 'Bar defines Str';

done-testing;

He does what I want in this simple case, and I still haven't done it:

ok 1 - The type 'Str' can do the method 'Str'
ok 2 - The type 'Foo' can do the method 'Str'
ok 3 - The type 'Bar' can do the method 'Str'
not ok 4 -
ok 5 -
1..5
# Failed test at /Users/brian/Desktop/hello.p6 line 12
# expected: 'Foo'
#      got: 'Mu'
# Looks like you failed 1 test of 5
+6
source share
1 answer

You cannot compare types by name.

my \Foo = anon class Foo {}
my \Bar = anon class Foo {}

say Foo.^name eq  Bar.^name; # True
say Foo       eqv Bar;       # False

is , .

is Bar.^lookup( 'Str' ).package, Bar, 'Bar defines Str'

, .

sub defines-method (
  Mu:U $class,
  Str:D $method,
  Str:D $desc = "$class.^name() defines $method"
) {
  is $class.^lookup( $method ).?package, $class, $desc
}

defines-method Foo, 'Str';

sub &infix:<defines-method> = &defines-method;

Bar defines-method 'Str';

( , .?package, .^lookup .)


.^lookup Method, ; , , , . , - (, ).
multi, .candidates .
( .^find_method, )

, .can, , , .*Str .+Str, . , .

> class Bar is Str { method Str { 'Hello' } }

> quietly .perl.say for Bar.+Str;
"Hello"
""
""

> .perl.say for Bar.new.+Str
"Hello"
""
"Bar<80122504>"

> quietly .(Bar).perl.say for Bar.can('Str')
"Hello"
""
""

> .(Bar.new).perl.say for Bar.can('Str')
"Hello"
""
"Bar<86744200>"
+7

All Articles