raku - Perl6 的角色中是否没有强制执行存根方法的类型签名?
问题描述
我正在尝试用 Perl6 做一些 OOP 并且在角色方面遇到了一些麻烦。我试图以与 Java 接口类似的方式使用它们,在那里我只有方法签名,必须由任何扮演该角色的类实现。我正在使用带有类型参数并返回的存根方法。
我注意到类型签名没有被强制执行,只有方法的名称。
示例脚本:
#!/usr/bin/env perl6
use v6;
role MyRole {
method intAdder( Int $a, Int $b --> Int ) { ... }
}
# this does the role and the method signature matches
class MyClass1 does MyRole {
method intAdder( Int $a, Int $b --> Int ) { return $a+$b }
}
# this does the role and the method signature does NOT match
# why is this allowed?
class MyClass2 does MyRole {
method intAdder( Str $a --> Str ) { return "Hello, $a." }
}
# this does the role and the method name does not match and gives an error as expected:
# Method 'intAdder' must be implemented by MyClass3 because it is required by roles: MyRole.
#
# class MyClass3 does MyRole {
# method adder( Int $a, Int $b --> Int ) { return $a+$b }
# }
sub MAIN() {
my $object1 = MyClass1.new;
my $object2 = MyClass2.new;
say $object1.intAdder: 40, 2;
say $object2.intAdder: 'world';
}
# output:
# 42
# Hello, world.
我已经阅读了官方文档中的面向对象页面,但找不到一种方法来做我想做的事......我也在尝试应用一种 Java 方式来思考 OOP 和打字,也许有不同的,更多Perl6ish 做我想做的事...
解决方案
如果你multi method
在角色中声明了一个使用方法,那么 P6 会强制multi method
消费者中有一个具有匹配签名的 a。(它也允许其他签名。)
如果省略multi
角色中的 ,P6 不会强制签名,只会在使用者中声明具有匹配名称的方法。
我不知道为什么它会这样工作。
2020 年更新在我对 SO“乐库中角色的签名限制”的回答中,请参阅我的评论开头“我认为设计意图是支持多态组合的两个概念” 。(2020 年的问题是这个问题的欺骗,但我不记得这个问题,不幸的是我搜索时也没有找到。)
推荐阅读
- python - 如何在python中对二进制图像进行组件标记
- r - 在层次列表中搜索名称(命名矩阵)并将输出放在数组或列表中 (r)
- android - Database_Impl 不存在 - 带有 Room 的 Android 应用
- reactjs - AsyncTypeahead 结果未显示在屏幕上
- r - 在 `R` 的 `gplots` 中,我们如何在 `heatmap.2` 函数中调整 x-label 刻度的位置?
- python - 如何使用 .grid 使用 tkinter 格式化我的 GUI?
- python - 如何将大数字拆分为单个数字?
- python - 如何使用opencv将鱼眼相机拍摄的图像转换为平面(矩形)图像?
- http - 尝试使用 ngrok 服务器时出现 404 NOT FOUND 错误
- scala - 寻找在 Scala 中动态组合函数的最佳实践