如何定义“ AT-POS”方法?

时间:2019-02-14 08:22:55

标签: operator-overloading perl6

我为一个类定义了AT-POS方法,并导出了[]运算符。 但是,当我在该类的实例上使用[]时,编译器将忽略我定义的运算符。

代码如下:

unit module somelib;

class SomeClass is export {
    method AT-POS(@indices) {
        say "indices are {@indices.perl}"
    }
}

multi postcircumfix:<[ ]> (SomeClass:D $inst, *@indices) is export {
    $inst.AT-POS(@indices)
}
#! /usr/bin/env perl6

use v6.c
use lib ".";
use somelib;

my $inst = SomeClass.new;

$inst[3, 'hi'];

# expected output:
#   indices are 3, 'hi'

# actual output:
#   Type check failed in binding to parameter '@indices';
#   expected Positional but got Int (3)
#     in method AT-POS at xxx/somelib.pm6 (somelib) line 4
#     in block <unit> at ./client.pl6 line 8

那么这段代码有什么问题?

更新:

我确实需要将多个索引传递给AT-POS方法,我很惊讶地发现,在修正拼写错误时,使用* $ indices而不是* @ indices可以得到预期的输出。我不知道是否存在* $ some-parameter之类的用法。是有效的还是只是编译器的错误?

unit module somelib;

class SomeClass is export {
    method AT-POS($indices) {
        say "indices are {$indices.perl}"
    }
}

multi postcircumfix:<[ ]> (SomeClass:D $inst, *$indices) is export {
    $inst.AT-POS($indices)
}
#! /usr/bin/env perl6

use v6.c;
use lib ".";
use somelib;

my $inst = SomeClass.new;

$inst[3, 'hi'];

# expected output:
#   indices are 3, 'hi' # or something like it 

# actual output:
#   indices are $(3, "hi") # It's ok for me.

1 个答案:

答案 0 :(得分:11)

问题在于,try { //connect,... } catch(SMTPSendFailedException e) { int errorCode = e.getReturnCode(); //f.e: 401 //check what error message the code relates, print it, etc.. } 仅预期接收一维AT-POS的单个参数。如果您指定切片,则该设置将多次调用Positional并将结果收集到列表中。

AT-POS

此外,您不需要提供class A { method AT-POS($a) { 2 * $a } } dd A.new[1,2,3,4]; # (2,4,6,8) 候选人,除非您真的想做非常特别的事情:所提供的设置将自动为您分配到正确的postcircumfix:<[ ]>