如何委托Scala中的成员?

时间:2011-03-29 18:22:09

标签: scala proxy

在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上调用相应的方法?

2 个答案:

答案 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