I have a method, with have a lot of implicit parameters:
def hello(message:String)(implicit a:A,b:B,c:C, ..., user: User) = {...}
Now consider such a class:
object Users extends Controller {
implicit a: A = ...
implicit b: B = ...
...
def index(id:String) = Action {
User.findById(id) match {
case Some(user) => {
implicit val _user = user
hello("implicit")
}
case _ => BadRequest
}
}
}
You can see this line in the above sample:
implicit val _user = user
It exists just to make the object user as an implicit object. Otherwise, I have to call hello as:
hello("implicit")(a,b,c,... user)
I’m thinking if there is any way to improve the code, e.g. we don’t need to define that _user variable but make the user is implicit.
Yes, there is a way to eliminate
_uservariable while makinguserimplicit:UPDATE: Addressing your question about many cases in the comments below.
It all depends what value type is returned by
User.findById. If it’sOption[User]but you want to match on specific users (assumingUseris a case class), then the original solution still applies:Or you can match on anything else if you want, as long as
User.findByIdisString => Option[User]If, on the other hand,
User.findByIdisString => Userthen you can simply define a helper object like:And use it as follows (again assuming
Useris a case class):or matching on some other value, say an
Int:I hope this covers all the scenarios you may have.