【问题标题】:Syntax of the method of an instantiated object: can't seem to get it right实例化对象的方法语法:似乎无法正确
【发布时间】:2018-07-22 09:05:55
【问题描述】:

我想获得一个对象方法的指针,例如这个类

class Foo { 
    has $thing = "baz"; 
    method bar() { say $thing }
}; 

sub quux( Callable $flimflam ) { 
    $flimflam() 
}; 
my $foo = Foo.new;

我想获取$foo.bar 方法指针以将其传递给quux。然而,这

quux(&($foo.bar))

Type check failed in binding to parameter '$flimflam'; expected Callable but got Bool (Bool::True)␤ in sub quux 失败

这也不行

quux($foo.bar)

也许是因为它没有参数;但是,如果我们将bar 的定义更改为:

 method bar($some ) { say $some ~ $thing }

然后上面调用的错误变成Too few positionals passed; expected 2 arguments but got 1␤ in method bar,错误爬到bar本身,这意味着对象本身没有进入。

我有checked out this answer,但它是用于类方法(新),它涉及使用元对象协议。会有更简单的方法吗?

【问题讨论】:

    标签: functional-programming raku


    【解决方案1】:

    您可以使用.^lookup 获取“静态”方法(@​​987654323@ 表示它是对元对象的调用)。

    该方法不会以任何方式绑定到调用者$foo,因此您必须将其称为

    class Foo { 
        has $thing = "baz"; 
        method bar() { say $thing }
    }; 
    
    sub quux( Callable $flimflam ) { 
        $flimflam() 
    }; 
    my $foo = Foo.new;
    
    my $method_bar = $foo.^lookup('bar');
    $method_bar($foo);
    

    您可以使用闭包将方法绑定到调用者:

    my $bound_method = -> |c { $method_bar($foo, |c) }
    

    Perl 6 还为此内置了一个快捷方式:

    my $bound_method = $method_bar.assuming($foo);
    

    但是你可以看到你可以将整个事情缩写为

    my $callback = { $foo.bar() }
    

    或者如果该方法可能需要更多参数

    my $callback = -> |c { $foo.bar(|c) }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-08
      • 2012-05-06
      • 1970-01-01
      • 2012-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多