如何在 Scala 中链接隐式?
pimp-my-library 模式允许我通过提供从类到实现该方法的隐式转换来看似向类添加方法。
然而,Scala 不允许发生两次这样的隐式转换,因此我无法使用隐式 A
到 从
和另一个隐式 A
到 C
BB
到 C
。有办法绕过这个限制吗?
The pimp-my-library pattern allows me to seemingly add a method to a class by making available an implicit conversion from that class to one that implements the method.
Scala does not allow two such implicit conversions taking place, however, so I cannot got from A
to C
using an implicit A
to B
and another implicit B
to C
. Is there a way around this restriction?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Scala 对添加方法的自动转换有限制,即在尝试查找方法时不会应用多个转换。例如:
编辑:自 Scala 2.11 起已弃用视图边界 ('<%') https://issues.scala-lang.org/browse/SI-7629(您可以使用类型类代替)
但是,如果隐式定义本身需要隐式参数(视图绑定), Scala将根据需要寻找其他隐式值。继续上一个例子:
“魔术!”,你可能会说。并非如此。以下是编译器如何翻译每个转换:
因此,虽然
bToC
被用作隐式转换,但aToB
和toA
被传递为隐式参数,而不是作为隐式转换链接起来。编辑
感兴趣的相关问题:
Scala has a restriction on automatic conversions to add a method, which is that it won't apply more than one conversion in trying to find methods. For example:
EDIT: View bounds ('<%') are deprecated since Scala 2.11 https://issues.scala-lang.org/browse/SI-7629 (You can use type classes instead)
However, if an implicit definition requires an implicit parameter itself(View bound), Scala will look for additional implicit values for as long as needed. Continue from the last example:
"Magic!", you might say. Not so. Here is how the compiler would translate each one:
So, while
bToC
is being used as an implicit conversion,aToB
andtoA
are being passed as implicit parameters, instead of being chained as implicit conversions.EDIT
Related question of interest:
请注意,您也可以使用隐式参数构建圆圈。然而,这些是由编译器检测到的,如下所示:
但是,给用户的错误并不像它们应有的那么清楚;它只是抱怨
无法找到所有三个建筑工地参数的隐式值
。在不太明显的情况下,这可能会掩盖根本问题。Note that you can build circles with implicit parameters, too. Those are, however, detected by the compiler, as exhibited by this:
The error(s) given to the user are not as clear as they could be, though; it just complains
could not find implicit value for parameter
for all three construction site. That might obscure the underlying problem in less obvious cases.这里一段代码也可以累积路径。
Here's a code that also accumulates the path.