우리는 종종 액션을 수행하는 사용자와 같은 코드 컨텍스트 정보를 전달해야합니다. 권한 부여 검사와 같은 다양한 작업에이 컨텍스트를 사용합니다. 이러한 경우 암묵적인 값은 보일러 플레이트 코드를 줄이는 데 매우 유용 할 수 있습니다. Akka 배우 만 작업 할 때 패턴 일치에서 스칼라 암시 적 추출 값?
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
}
나는 최근 자신이 작업을 수행 할 필요가에서 발견
case class EC(initiatingUser:User)
우리가 가질 수있는 편리한 가드 :
의 우리가 우리 주위에 통과 간단한 실행 컨텍스트 있다고 가정 해 봅시다 그들은 패턴 매칭 (pattern matching)을 사용하고 있으며, 아직 추출기 (extractor)와 함축 된 implicits를 만드는 좋은 방법을 찾고 있습니다.
먼저 당신은 모든 명령 컨텍스트를 통과해야하지만 간단합니다 :
case class DeleteCommand(entityId:Long)(implicit executionContext:EC)
//note that you need to overwrite unapply to extract that context
하지만 기능은 다음과 같습니다 나타납니다
class MyActor extends Actor{
def receive = {
case DeleteCommand(entityId, context) => {
implicit val c = context
sender ! onlyAdmins{
//do something adminy that also uses context
}
}
}
}
그것은 추출 된 변수의 경우 훨씬 더 간단 것 암시 적으로 표시 될 수 있지만이 기능을 보지 못했습니다.
def receive = {
case DeleteCommand(entityId, implicit context) => sender ! onlyAdmins{
//do something adminy (that also uses context)
}
}
Ar e를 코딩하는 대안적인 방법을 알고 있으므로 상용구 코드가 줄어 듭니다.
당신이에 관심이있을 수는 : http://stackoverflow.com/questions/6156656/how-to-pattern-match-a-class-with-multiple-argument-lists – gzm0
이 무엇 GADTs 같은 소리 typeclass context와 implicits의 유사성을 고려한다면 Haskell에서 할 수있다. 스칼라에서 GADT와 유사한 패턴 매칭을 수행하는 더 원칙적인 방법을 제공 할 수도 있습니다. –