Guest User

Untitled

a guest
Nov 21st, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. package com.github.diegopacheco.scalaplayground.typeclasses
  2.  
  3. object CanTalkMainApp extends App {
  4.  
  5. final case class Person(name:String)
  6. final case class Cat(name:String)
  7.  
  8. trait CanTalk[T]{
  9. def talk(talker:T): String
  10. }
  11.  
  12. object AddOns{
  13.  
  14. implicit object PersonTalker extends CanTalk[Person]{
  15. def talk(p:Person):String = s"Hi, I'm ${p.name}"
  16. }
  17.  
  18. implicit object CatTalker extends CanTalk[Cat]{
  19. def talk(c:Cat):String = s"burun burun burun (${c.name})"
  20. }
  21.  
  22. implicit class TalkUtil[A](x:A){
  23. def talk(implicit talker:CanTalk[A]):String = talker.talk(x)
  24. }
  25.  
  26. }
  27.  
  28. import AddOns._
  29. println( Person("Diego").talk )
  30. println( Cat("Gandalhy").talk )
  31.  
  32. final case class Dog(name:String)
  33. implicit object DogTalker extends CanTalk[Dog]{
  34. def talk(d:Dog):String = s"rof rof (${d.name})"
  35. }
  36. import DogTalker._
  37.  
  38. println( Dog("Dunginha").talk )
  39.  
  40. }
Add Comment
Please, Sign In to add comment