在Scala中重载通用事件处理程序
发布时间:2020-12-16 19:17:32  所属栏目:安全  来源:网络整理 
            导读:如果我定义以下通用事件处理程序 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 Eve
                
                
                
            | 
 如果我定义以下通用事件处理程序 
  
  
  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) = {
    }
  }但斯卡拉抱怨说,一个特质不能被遗传两次. 我发现这个answer暗示了一个解决方案,但它接缝需要多个类(每个处理程序一个).这真的是唯一的方法,还是有一些其他的Scala构造,我可以使用它来使单个类实现多个通用事件处理程序(即使用案例类,清单或其他一些奇特的构造)? 解决方法
 我不知道在一个类中做到这一点的方法(除了通过使事件成为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)
  ...
}(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! | 
