在Scala中重载泛型事件处理程序
如果我定义以下通用事件处理程序在Scala中重载泛型事件处理程序,scala,type-erasure,reification,Scala,Type Erasure,Reification,如果我定义以下通用事件处理程序 trait Handles[E <: Event] { def handle(event: E) } 然后,如何创建一个类来实现这些事件的事件处理程序?。我试过: class InventoryListView extends Handles[InventoryItemCreated] with Handles[InventoryItemDeactivated] { def handle(event: InventoryItemCreated)
trait Handles[E <: Event] {
def handle(event: E)
}
然后,如何创建一个类来实现这些事件的事件处理程序?。我试过:
class InventoryListView extends Handles[InventoryItemCreated] with Handles[InventoryItemDeactivated] {
def handle(event: InventoryItemCreated) = {
}
def handle(event: InventoryItemDeactivated) = {
}
}
但Scala抱怨说,一个特征不能被遗传两次
我发现这暗示了一个解决方案,但它需要多个类(每个处理程序一个)。这真的是唯一的方法吗?或者是否有其他Scala构造可以用来使单个类实现多个通用事件处理程序(即使用case类、清单或其他奇特的构造) 我不知道如何在一个类中实现这一点(除了将
事件
设置为ADT并定义句柄以接受事件
类型的参数。但这将消除您似乎正在寻找的类型安全性)
我建议改用类型类模式
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)
...
}
trait Handles[-A,-E两种独立的handle
方法的优点是什么
def handle(rawEvent: Event) = rawEvent match {
case e: InventoryItemCreated => ...
case e: InventoryItemDeactivated => ...
}
def handle(rawEvent: Event) = rawEvent match {
case e: InventoryItemCreated => ...
case e: InventoryItemDeactivated => ...
}