我如何委托给 Scala 中的成员?
在Scala中是否可以写这样的东西:
trait Road {
...
}
class BridgeCauseway extends Road {
// implements method in Road
}
class Bridge extends Road {
val roadway = new BridgeCauseway()
// delegate all Bridge methods to the `roadway` member
}
或者我需要一一实现Road
的每个方法,并在roadway
上调用相应的方法?
Is it possible in Scala to write something like:
trait Road {
...
}
class BridgeCauseway extends Road {
// implements method in Road
}
class Bridge extends Road {
val roadway = new BridgeCauseway()
// delegate all Bridge methods to the `roadway` member
}
or do I need to implement each of Road
's methods, one by one, and call the corresponding method on roadway
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实现此目的的最简单方法是使用隐式转换而不是类扩展:
只要您不需要携带原始的
Bridge
(例如,您要存储Road
集合中的Bridge
)。如果您确实需要再次取回
Bridge
,您可以在Road
中添加owner
方法,该方法返回Any
>,使用BridgeCauseway
的构造函数参数进行设置,然后进行模式匹配以获取桥梁:The easiest way to accomplish this is with an implicit conversion instead of a class extension:
as long as you don't need the original
Bridge
to be carried along for the ride (e.g. you're going to storeBridge
in a collection ofRoad
).If you do need to get the
Bridge
back again, you can add anowner
method inRoad
which returns anAny
, set it using a constructor parameter forBridgeCauseway
, and then pattern-match to get your bridge:如果您可以将
Bridge
作为特质
,您就会被排序。If you can make
Bridge
atrait
you'll be sorted.