如何在Scala中使用抽象类型成员组合分层服务

时间:2014-03-16 09:18:43

标签: scala

如何根据处理抽象类型的几个分层服务接口来描述API接口,其表示可以通过具体实现来选择。

// interfaces

trait API {
  val serviceA: ServiceA
  val serviceB: ServiceB[ServiceA]
  def op_API: Unit = serviceA.op_A(serviceB.op_B)
}

trait ServiceA {
  type X
  def op_A(x: X): Unit
}

trait ServiceB[A <: ServiceA] {
  def op_B: A#X
}

// implementations

object API_Impl extends API {
  val serviceA = ServiceA_Impl
  val serviceB = ServiceB_Impl
}

object ServiceA_Impl extends ServiceA {
  type X = String
  def op_A(x: String): Unit = println(x)
}

object ServiceB_Impl extends ServiceB[ServiceA_Impl.type] {
  def op_B: String = "test"
}

不幸的是,此代码会导致类型不匹配:

found   : ServiceA#X
required: API.this.serviceA.X
 def op_API: Unit = serviceA.op_A(serviceB.op_B)
                                           ^

1 个答案:

答案 0 :(得分:0)

我认为一种方法是让外部服务层维护内部服务层的实例,根据该实例定义类型,然后通过外部服务成员分配API的服务成员层:

// interfaces

trait API {
  lazy val serviceA: serviceB.serviceA.type = serviceB.serviceA
  val serviceB: ServiceB[_ <: ServiceA]
  def op_API: Unit = serviceA.op_A(serviceB.op_B)
}

trait ServiceA {
  type X
  def op_A(x: X): Unit
}

trait ServiceB[A <: ServiceA] {
  val serviceA: A
  def op_B: serviceA.X
}

// implementations

object API_Impl extends API {
  val serviceB = ServiceB_Impl
}

object ServiceA_Impl extends ServiceA {
  type X = String
  def op_A(x: String): Unit = println(x)
}

object ServiceB_Impl extends ServiceB[ServiceA_Impl.type] {
  val serviceA = ServiceA_Impl
  def op_B: String = "test"
}