Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

Implicit keyword before a parameter in anonymous function in Scala

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 function:

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

What does the implicit keyword do here?

Are there resources on the web that describes more on what the use case is?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...