7

我有一个方法,有很多隐式参数:

def hello(message:String)(implicit a:A,b:B,c:C, ..., user: User) = {...}

现在考虑这样一个类:

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
     }
  }
}

您可以在上面的示例中看到这一行:

implicit val _user = user

它的存在只是为了使对象user成为隐式对象。否则,我必须调用hello

hello("implicit")(a,b,c,... user)

我在想是否有任何方法可以改进代码,例如我们不需要定义该_user变量,而是将其设为user隐式。

4

2 回答 2

6

是的,有一种方法可以在隐式的_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.findByIdString => 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
    }
  }
}

我希望这涵盖了您可能遇到的所有情况。

于 2012-03-10T02:32:21.510 回答
2

我不知道诸如案例之类的技巧,Some(implicit user)但是呢?

def hello(message: String, user: User)(implicit a: A, ... z: Z) = ...
def hello(message: String)(implicit a: A, ... z: Z, user: User) = hello(message, user)

case Some(user) => hello("implicit", user)
于 2012-03-09T12:42:01.413 回答