Skip to content

Instantly share code, notes, and snippets.

@fiadliel
Created August 16, 2015 14:35
Show Gist options
  • Save fiadliel/b317c36db9282188e23c to your computer and use it in GitHub Desktop.
Save fiadliel/b317c36db9282188e23c to your computer and use it in GitHub Desktop.
scala> import Implicits._
import Implicits._
scala> FirstEvent("hello")
res0: FirstEvent = FirstEvent(hello)
scala> res0.handle
res1: String = hello
scala> ThirdEvent("hello")
res2: ThirdEvent = ThirdEvent(hello)
scala> res2.handle
<console>:18: error: could not find implicit value for parameter handler: EventHandler[ThirdEvent,U]
res2.handle
^
trait Event
case class FirstEvent(firstHello: String) extends Event
case class SecondEvent(secondHello: String) extends Event
case class ThirdEvent(thirdHello: String) extends Event
trait EventHandler[T <: Event, U] {
def handle(event: T): U
}
object EventHandler {
implicit object FirstEventHandler extends EventHandler[FirstEvent, String] {
def handle(t: FirstEvent) = t.firstHello
}
implicit object SecondEventHandler extends EventHandler[SecondEvent, String] {
def handle(t: SecondEvent) = t.secondHello
}
}
object Implicits {
implicit class EventHandlerSyntax[T <: Event](event: T) {
def handle[U](implicit handler: EventHandler[T, U]): U =
handler.handle(event)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment