Guest User

Untitled

a guest
Jan 20th, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. sealed abstract trait Event
  2. case class SomeEvent(msg: String) extends Event
  3. case class OtherEvent(code: String) extends Event
  4.  
  5. // Assume library1 needs Show and library2 needs Printer
  6.  
  7. trait Show[A] { def show(a: A): String }
  8. trait Printer[A] { def printIt(a: A): Unit }
  9.  
  10. object ShowInstances {
  11. implicit val showSomeEvent = new Show[SomeEvent] {
  12. override def show(a: SomeEvent) =
  13. s"SomeEvent: ${a.msg}"
  14. }
  15.  
  16. implicit val showOtherEvent = new Show[OtherEvent] {
  17. override def show(a: OtherEvent) =
  18. s"OtherEvent: ${a.code}"
  19. }
  20. }
  21.  
  22. object PrinterInstances {
  23. implicit def somePrinter[A: Show]: Printer[A] = new Printer[A] {
  24. override def printIt(a: A): Unit =
  25. println(implicitly[Show[A]].show(a))
  26. }
  27. }
  28.  
  29. object EventHandler {
  30.  
  31. private def printEvent[A <: Event](a: A)(implicit printer: Printer[A]): Unit = {
  32. print("Handling event: ")
  33. printer.printIt(a)
  34. }
  35.  
  36. def handle(a: Event): Unit = {
  37. import ShowInstances._
  38. import PrinterInstances._
  39.  
  40. // I'd like to do this:
  41. //EventHandler.printEvent(a)
  42.  
  43. // but I have to do this
  44. a match {
  45. case s: SomeEvent => EventHandler.printEvent(s)
  46. case o: OtherEvent => EventHandler.printEvent(o)
  47. }
  48. }
  49. }
Add Comment
Please, Sign In to add comment