如何在Raku中创建一个与内置类同名但不会遮盖它的类?

huangapple go评论65阅读模式
英文:

How do I create a class with the same name as a built-in one without overshadowing it in Raku?

问题

这是相当愚蠢的,我知道明显的做法只是简单地为类取一个不同的名称,但我仍然很好奇。在ColumnType::Date类中,我想要typecast方法返回一个Raku的Date对象,而不是ColumnType::Date对象:

module ColumnType {
    class Date {
        method typecast(Blob:D $value) {
            my $date = $value.decode('ascii').trim;
            my ($year, $month, $day) = $date.split('/');
            return try Date.new: :$year, :$month, :$day;
        }
    }
}

my $blob = "1980/01/01".encode('ascii');
say ColumnType::Date.new.typecast($blob);

换句话说,是否可以使用完全限定的名称引用Raku的Date

英文:

This is quite silly and I know the obvious thing to do is simply naming the class differently but I'm still curious. In the class ColumnType::Date, I'd like typecast to return a Raku's Date object, and not a ColumnType::Date one:

module ColumnType {
    class Date {
        method typecast(Blob:D $value) {
            my $date = $value.decode('ascii').trim;
            my ($year, $month, $day) = $date.split('/');
            return try Date.new: :$year, :$month, :$day;
        }
    }
}

my $blob = "1980/01/01".encode('ascii');
say ColumnType::Date.new.typecast($blob);

In other words, is it possible to reference Raku's Date as a fully-qualified name?

答案1

得分: 10

是的。通过前缀 CORE::

$ raku -e 'say CORE::Date =:= Date'
True

编辑:

更一般地说,您可以通过使用 my constant 在词法上覆盖后访问词法可用的东西。在您的示例中,您也可以这样做:

module ColumnType {
    my constant OriginalDate = Date;
    class Date {
        method typecast(Blob:D $value) {
            my $date = $value.decode('ascii').trim;
            my ($year, $month, $day) = $date.split('/');
            return try OriginalDate.new: :$year, :$month, :$day;
        }
    }
}

这将在模块内将类 Date 的可见性保存为 OriginalDate,然后您可以使用它来调用 .new

英文:

Yes. By prefixing CORE::.

$ raku -e 'say CORE::Date =:= Date'
True

EDIT:

More generally, you can access something that is lexically available after lexically overriding it, by using my constant. In your example, you could also have done:

module ColumnType {
    my constant OriginalDate = Date;
    class Date {
        method typecast(Blob:D $value) {
            my $date = $value.decode('ascii').trim;
            my ($year, $month, $day) = $date.split('/');
            return try OriginalDate.new: :$year, :$month, :$day;
        }
    }
}

This will "save" the visibility of the class Date inside the module as OriginalDate, which you can then use to call .new on.

huangapple
  • 本文由 发表于 2023年7月17日 22:02:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76705230.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定