在模式匹配中隐含

时间:2012-03-09 11:30:15

标签: scala playframework-2.0 pattern-matching implicit

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

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

2 个答案:

答案 0 :(得分:5)

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

我希望这涵盖了您可能拥有的所有场景。

答案 1 :(得分: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)
相关问题