scala隐式提取模式匹配中的值?

Cri*_*bie 5 scala implicit pattern-matching akka

我们经常需要传递代码上下文信息,例如执行操作的用户.我们将此上下文用于授权检查等各种事务.在这些情况下,隐含值可以证明对减少锅炉板代码非常有用.

假设我们传递了一个简单的执行上下文: case class EC(initiatingUser:User)

我们可以有方便的守卫:

def onlyAdmins(f: => T)(implicit context:EC) = context match{
  case EC(u) if(u.roles.contain(Role.ADMIN)) => f
  case _ => throw new UnauthorizedException("Only admins can perform this action")
}

val result = onlyAdmins{
  //do something adminy 
}
Run Code Online (Sandbox Code Playgroud)

我最近发现自己需要在与Akka演员合作时这样做,但他们使用模式匹配,我还没有找到一个很好的方法来使implicits与提取器一起工作.

首先,您需要使用每个命令传递上下文,但这很简单:

case class DeleteCommand(entityId:Long)(implicit executionContext:EC)
//note that you need to overwrite unapply to extract that context
Run Code Online (Sandbox Code Playgroud)

但是接收函数看起来像这样:

class MyActor extends Actor{
  def receive = {
     case DeleteCommand(entityId, context) => {
       implicit val c = context
       sender ! onlyAdmins{
         //do something adminy that also uses context
       }
     }
  }
}
Run Code Online (Sandbox Code Playgroud)

如果提取的变量可以标记为隐式但是我没有看到这个特性会更简单:

def receive = {
  case DeleteCommand(entityId, implicit context) => sender ! onlyAdmins{
    //do something adminy (that also uses context)
  }
}
Run Code Online (Sandbox Code Playgroud)

您是否了解任何其他编码方式,以减少样板代码?

cmb*_*ter 1

我认为您正在向案例类添加多个参数集和隐式参数,并且还必须添加新的参数集,这一事实unapply可能表明您正在走一条不太好的道路。虽然这些类型的事情是可能的,但它们可能不是一个好主意,也许案例类上的多个参数集(和隐式)之类的东西有一天可能会消失。我用更标准的东西重写了你的例子。我并不是说这是一个完美的解决方案,但它更符合标准路径:

trait ContextCommand{
  def context:EC
}

case class DeleteCommand(entityId:Long, context:EC) extends ContextCommand


def onlyAdmins[T](cmd:ContextCommand)(f: => T) = cmd.context match {
  case EC(u) if(u.roles.contain(Role.ADMIN)) => f
  case _ => throw new UnauthorizedException("Only admins can perform this action")    
}

class MyActor extends Actor{
  def receive = {
     case cmd @ DeleteCommand(entityId, ctx) => {
       sender ! onlyAdmins(cmd){
         //do something adminy that also uses context
         //Note, ctx available here via closure
       }
     }
  }
}
Run Code Online (Sandbox Code Playgroud)