Advertisement
NLinker

Passing functions having implicit parameters

Dec 7th, 2017
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.93 KB | None | 0 0
  1.  
  2. // The output is
  3. // List(Apple(1:Semerenka), Apple(1:Gloster), Apple(1:Red Prince))
  4. // List(Orange(1:Turkey), Orange(1:Egypt))
  5. // List(Peach(1:Yes!), Peach(1:Sure!))
  6. // List(Apple(2:Semerenka), Apple(2:Gloster), Apple(2:Red Prince))
  7. // List(Orange(2:Turkey), Orange(2:Egypt))
  8. // List(Peach(2:Yes!), Peach(2:Sure!))
  9.  
  10. trait Session {
  11.   override def toString: String = this match {
  12.     case ReadOnlySession ⇒ "1"
  13.     case NormalSession ⇒ "2"
  14.   }
  15. }
  16. object ReadOnlySession extends Session
  17. object NormalSession extends Session
  18.  
  19. object Test {
  20.   def main(args: Array[String]): Unit = {
  21.     implicit val session: Session = ReadOnlySession
  22.     val normSession = NormalSession
  23.  
  24.     val list1 = genericList1(Apple.findAll)
  25.     val list2 = genericList2(Orange.findAll)
  26.     val list3 = genericList3(Peach.findAll()(_))
  27.     val list4 = genericList1(Apple.findAll()(normSession))
  28.     val list5 = genericList2(() ⇒ Orange.findAll()(normSession))
  29.     val list6 = genericList3(Peach.findAll()(_))(normSession)
  30.  
  31.     println(list1)
  32.     println(list2)
  33.     println(list3)
  34.     println(list4)
  35.     println(list5)
  36.     println(list6)
  37.   }
  38.  
  39.   def genericList1[A](method: ⇒ List[A]): List[A] = {
  40.     method
  41.   }
  42.  
  43.   def genericList2[A](method: () ⇒ List[A]): List[A] = {
  44.     method()
  45.   }
  46.  
  47.   def genericList3[A](method: Session ⇒ List[A])(implicit session: Session): List[A] = {
  48.     method(session)
  49.   }
  50.  
  51.   case class Apple(sort: String)
  52.   object Apple {
  53.     def findAll()(implicit s: Session): List[Apple] = {
  54.       List(Apple(s"$s:Semerenka"), Apple(s"$s:Gloster"), Apple(s"$s:Red Prince"))
  55.     }
  56.   }
  57.  
  58.   case class Orange(country: String)
  59.   object Orange {
  60.     def findAll()(implicit s: Session): List[Orange] =
  61.       List(Orange(s"$s:Turkey"), Orange(s"$s:Egypt"))
  62.   }
  63.  
  64.   case class Peach(tasty: String)
  65.   object Peach {
  66.     def findAll()(implicit s: Session): List[Peach] =
  67.       List(Peach(s"$s:Yes!"), Peach(s"$s:Sure!"))
  68.   }
  69.  
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement