首页 > 解决方案 > 覆盖方法调用运算符或其他方法来捕获方法名称解析错误

问题描述

我正在尝试为X::NYI该类编写一个示例作为对此问题的回应。我想出了这样的事情:

class Nothing {
    sub postfix:<.&>( $sub, **@args) {
        die X::NYI.new( feature => $sub,
                        did-you-mean => "nothing",
                        workaround => "Implement it yourself" );
    }
}

my $let's-see = Nothing.newish;

它试图重新实现方法调用后缀运算符,以便为任何被调用的东西抛出异常。这不起作用:

No such method 'newish' for invocant of type 'Nothing'

在 NYI.p6 第 13 行的街区

而且,事实上,文档说:

从技术上讲,不是真正的操作员;它是编译器中的特殊语法。

这很可能意味着它不能被覆盖。这也意味着做我想做的意味着与元模型交互以拦截类解析方法。但我真的不明白如何做到这一点。Rakudo 源代码中的大多数示例,例如这个示例,在调用具体函数时都会抛出异常,而实际上,我们看到的异常是由级别的dispatch方法Mu抛出的。

那么压倒一切dispatch是做这种事情的正确方法吗?还是其他完全不同的东西?

标签: ooprakudispatch

解决方案


我觉得你想要FALLBACK

https://docs.raku.org/language/typesystem#index-entry-FALLBACK_%28method%29

这将转化为:

class Nothing {
    method FALLBACK($name, |c) is hidden-from-backtrace {
        die X::NYI.new( feature => $name,
                        did-you-mean => "nothing",
                        workaround => "Implement it yourself" );
    }
}

my $a = Nothing.newish;
============================
newish not yet implemented. Sorry.
Did you mean: nothing?
Workaround: Implement it yourself
  in block <unit> at file line 10

请注意,我还使用了is hidden-from-backtracetrait 来确保FALLBACK回溯中没有提到该方法。


推荐阅读