在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
上调用相应的方法?
答案 0 :(得分:18)
实现此目的的最简单方法是使用隐式转换而不是类扩展:
class Bridge { ... }
implicit def bridge2road(b: Bridge) = b.roadway
只要您不需要随身携带原始Bridge
(例如,您要将Bridge
存储在Road
的集合中。< / p>
如果您确实需要再次返回Bridge
,可以在owner
中添加Road
方法,该方法返回Any
,使用构造函数参数设置它BridgeCauseway
,然后进行模式匹配以获得您的桥梁:
trait Road {
def owner: Any
...
}
class BridgeCauseway(val owner: Bridge) extends Road { . . . }
class Bridge extends Road {
val roadway = new BridgeCauseway(this)
...
}
myBridgeCauseway.owner match {
case b: Bridge => // Do bridge-specific stuff
...
}
答案 1 :(得分:3)
如果,您可以Bridge
trait
进行排序。
scala> trait A {
| val x: String
| }
defined trait A
scala> class B extends A {
| val x = "foo"
| val y = "bar"
| }
defined class B
scala> trait C extends A { self: B =>
| val z = "baz"
| }
defined trait C
scala> new B with C
res51: B with C = $anon$1@1b4e829
scala> res51.x
res52: java.lang.String = foo
scala> res51.y
res53: java.lang.String = bar
scala> res51.z
res54: java.lang.String = baz