Implicit keyword before a parameter in anonymous function in Scala

后端 未结 3 498
北海茫月
北海茫月 2020-11-29 04:37

I understand implicit parameters and implicit conversions in Scala but I saw this for the first time today: the implicit keyword in front of a parameter in an anonymous func

相关标签:
3条回答
  • 2020-11-29 05:07

    In my understanding, the keyword of Implicit means Let complier do the job

    Declaring an implicit variable means it can be used for implicit parameter of other methods inside the scope. In other words, the variable is being considered by the compiler to fill in implicit parameters.

     def index = Action { implicit request =>
        val str = sayHi("Jason")
        Ok(views.html.index("Your new application is ready." + str))
      }
    
      private def sayHi(name: String)(implicit req: Request[AnyContent]) = name + ", you can the following content" + req.body
    

    I declare an implicit parameter req in sayHi with type Request[AnyContent], however, I can call the method with only first parameter sayHi("Jason") because the implicit parameter req is filled in by the compiler to reference the implicit variable request

    0 讨论(0)
  • 2020-11-29 05:21

    There are two distinct features here.

    First, request isn't really an argument in a method invocation. It's the argument of an anonymous function. The anonymous function itself is the argument of the method invocation.

    Second, declaring an implicit argument in an anonymous function have the convenience of saving you from "forcing" a val into a implicit:

    Action { request =>
      implicit val r = request
      Ok("Got request [" + request + "]")
    }
    

    I happen to know this a Play framework code, but I am not sure what are the signatures for Action and Ok. I will guess that they are something like that:

    def Action(r:Request => Result):Unit
    case class Ok(str:msg)(implicit r:Request)
    

    Again, it's pure guessing for illustrative purposes only.

    0 讨论(0)
  • 2020-11-29 05:25

    Found a few resources:

    https://issues.scala-lang.org/browse/SI-1492

    https://stackoverflow.com/a/5015161/480674

    search for "Implicit arguments in closures" on the second link

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