如果我定义以下通用事件处理程序
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 构造可以用来让单个类实现多个通用事件处理程序(即使用案例类、清单或其他一些奇特的构造)?
我不知道有什么方法可以在一堂课上做到这一点(除了通过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)
...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)