Overloading generic event handlers in Scala

后端 未结 2 761
花落未央
花落未央 2021-01-12 13:13

If I define the following generic event handler

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

with event type\'s like this

<
相关标签:
2条回答
  • 2021-01-12 13:18

    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)
      ...
    }
    
    0 讨论(0)
  • 2021-01-12 13:34

    What's the advantage of two separate handle methods?

    def handle(rawEvent: Event) = rawEvent match {
      case e: InventoryItemCreated => ...
      case e: InventoryItemDeactivated => ...
    }
    
    0 讨论(0)
提交回复
热议问题