Created
August 16, 2015 14:35
-
-
Save fiadliel/b317c36db9282188e23c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
^ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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