是的,有一种方法可以在隐式的_user
同时消除变量:user
def index(id:String) = Action {
User.findById(id) map (implicit user => hello("implicit")) getOrElse BadRequest
}
更新:在下面的评论中解决您关于许多案例的问题。
这完全取决于返回的值类型User.findById
。如果是,Option[User]
但您想匹配特定用户(假设User
是一个案例类),那么原始解决方案仍然适用:
def index(id:String) = Action {
User.findById(id) map { implicit user =>
user match {
case User("bob") => hello("Bob")
case User("alice") => hello("Alice")
case User("john") => hello("John")
case _ => hello("Other user")
}
} getOrElse BadRequest
或者您可以根据需要匹配其他任何东西,只要User.findById
是String => Option[User]
另一方面,如果User.findById
是,String => User
那么您可以简单地定义一个辅助对象,例如:
object withUser {
def apply[A](user: User)(block: User => A) = block(user)
}
并按如下方式使用它(再次假设User
是一个案例类):
def index(id: String) = Action {
withUser(User findById id) { implicit user =>
user match {
case User("bob") => hello("Bob")
case User("alice") => hello("Alice")
case User("john") => hello("John")
case _ => BadRequest
}
}
}
或匹配其他值,例如Int
:
def index(id: String, level: Int) = Action {
withUser(User findById id) { implicit user =>
level match {
case 1 => hello("Number One")
case 2 => hello("Number Two")
case 3 => hello("Number Three")
case _ => BadRequest
}
}
}
我希望这涵盖了您可能遇到的所有情况。