英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论