Implicit parameter for literal function

前端 未结 1 1054
执念已碎
执念已碎 2021-01-20 01:23

While reading Play! Framework documentation, I came across this snippet:

def index = Action { implicit request =>
  session.get(\"connected\").map { user          


        
相关标签:
1条回答
  • 2021-01-20 02:14

    Consider the following code:

    class MyImplicitClass(val session: Int)
    object Tester {
      def apply(fun: MyImplicitClass => Int): Int = ???
      def apply(fun: => Int): Int = ???
    }
    Tester { implicit myImplicitClass => session * 20}
    

    If this function:

    def session(implicit myImplicitClass: MyImplicitClass): Int = myImplicitClass.session
    

    is in scope, then the first code snippet will compile, because clearly the implicit parameter myImplicitClass will be passed to the function session in order to access the field myImplicitClass.session, allowing you to omit the field access. This is exactly the trick the Play! Framework is using, check Controller to find the session function.

    As a side note, the above closure is not stating that it takes an implicit parameter, it's a language feature to avoid having to do the following:

    Tester { myImplicitClass => 
      implicit val x = myImplicitClass
      session * 20
    }
    

    when one wants to use a closure parameter as an implicit value in the body of the closure. Also note that as of Scala 2.9, you are limited to closures with exactly 1 parameter for this trick.

    0 讨论(0)
提交回复
热议问题