Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- sealed abstract trait Event
- case class SomeEvent(msg: String) extends Event
- case class OtherEvent(code: String) extends Event
- // Assume library1 needs Show and library2 needs Printer
- trait Show[A] { def show(a: A): String }
- trait Printer[A] { def printIt(a: A): Unit }
- object ShowInstances {
- implicit val showSomeEvent = new Show[SomeEvent] {
- override def show(a: SomeEvent) =
- s"SomeEvent: ${a.msg}"
- }
- implicit val showOtherEvent = new Show[OtherEvent] {
- override def show(a: OtherEvent) =
- s"OtherEvent: ${a.code}"
- }
- }
- object PrinterInstances {
- implicit def somePrinter[A: Show]: Printer[A] = new Printer[A] {
- override def printIt(a: A): Unit =
- println(implicitly[Show[A]].show(a))
- }
- }
- object EventHandler {
- private def printEvent[A <: Event](a: A)(implicit printer: Printer[A]): Unit = {
- print("Handling event: ")
- printer.printIt(a)
- }
- def handle(a: Event): Unit = {
- import ShowInstances._
- import PrinterInstances._
- // I'd like to do this:
- //EventHandler.printEvent(a)
- // but I have to do this
- a match {
- case s: SomeEvent => EventHandler.printEvent(s)
- case o: OtherEvent => EventHandler.printEvent(o)
- }
- }
- }
Add Comment
Please, Sign In to add comment