Overloading generic event handlers in Scala

試著忘記壹切 提交于 2019-12-01 04:15:48

I don't know of a way to do it in one class (except by making Event an ADT and defining handle to accept a parameter of type Event. But that would take away the kind of typesafety you seem to be looking for).

I'd suggest using type-class pattern instead.

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)
  ...
}

What's the advantage of two separate handle methods?

def handle(rawEvent: Event) = rawEvent match {
  case e: InventoryItemCreated => ...
  case e: InventoryItemDeactivated => ...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!