在Scala中重载通用事件处理程序

时间:2011-12-20 21:54:53

标签: scala type-erasure reification

如果我定义以下通用事件处理程序

trait Handles[E <: Event] {
  def handle(event: E)
}

事件类型是这样的

trait Event {

}
class InventoryItemDeactivated(val id: UUID) extends Event;

class InventoryItemCreated(val id: UUID, val name: String) extends Event;

然后我如何创建一个为每个事件实现事件处理程序的类?我试过了:

class InventoryListView extends Handles[InventoryItemCreated] with Handles[InventoryItemDeactivated] {
    def handle(event: InventoryItemCreated) = {

    }

    def handle(event: InventoryItemDeactivated) = {

    }
  }

但Scala抱怨说,一个特征不能被遗传两次。

我发现这个answer暗示了一个解决方案,但它接缝需要多个类(每个处理程序一个)。这是否真的是唯一的方法,或者是否有一些其他Scala构造我可以用来使单个类实现多个通用事件处理程序(即使用案例类,清单或其他一些奇特的构造)?

2 个答案:

答案 0 :(得分:11)

我不知道在一个类中做到这一点的方法(除了使Event成为ADT并定义句柄以接受Event类型的参数。但这会带走那种类型您似乎正在寻找的类型安全。)

我建议使用类型模式。

trait Handles[-A, -E <: Event] {
  def handle(a: A, event: E)
}

trait Event {
  ...
}
class InventoryItemDeactivation(val id: UUID) extends Event
class InventoryItemCreation(val id: UUID, val name: String) extends Event

class InventoryListView {
  ...
}

implicit object InventoryListViewHandlesItemCreation extends 
    Handles[InventoryListView, InventoryItemCreation] = {
  def handle(v: InventoryListView, e: InventoryItemCreation) = {
    ...
  }
}

implicit object InventoryListViewHandlesItemDeactivation extends 
    Handles[InventoryListView, InventoryItemDeactivation] = {
  def handle(v: InventoryListView, e: InventoryItemDeactivation) = {
    ...
  }
}

def someMethod[A, E <: Event](a: A, e: E)
              (implicit ev: InventoryListView Handles InventoryItemCreation) = {
  ev.handle(a, e)
  ...
}

答案 1 :(得分:4)

两种单独的handle方法有什么优势?

def handle(rawEvent: Event) = rawEvent match {
  case e: InventoryItemCreated => ...
  case e: InventoryItemDeactivated => ...
}