当我提出这个想法时,我正试图在项目(Play Framework 2.4)中重构我的scala代码:
(为了提供一个最小的工作示例,我已经更改了一些类,例如,我分别使用Int和Option [Int]更改了Result和Future [Result])
object ParFuncApply {
trait CanBeAuthenticatedRequest[A]
trait AuthenticatedRequest[A] extends CanBeAuthenticatedRequest[A]
trait UnauthenticatedRequest[A] extends CanBeAuthenticatedRequest[A]
private def fold[T](authenticated: (AuthenticatedRequest[_]) => T)
(unauthenticated: (UnauthenticatedRequest[_]) => T):
PartialFunction[CanBeAuthenticatedRequest[_], T] = {
case ar: AuthenticatedRequest[_] => authenticated(ar)
case ur: UnauthenticatedRequest[_] => unauthenticated(ur)
}
def apply(request: CanBeAuthenticatedRequest[_])
(authenticated: (AuthenticatedRequest[_]) => Int)
(unauthenticated: (UnauthenticatedRequest[_]) => Int): Int = {
fold(authenticated)(unauthenticated)(request)
}
def async(request: CanBeAuthenticatedRequest[_])
(authenticated: (AuthenticatedRequest[_]) => Option[Int])
(unauthenticated: (UnauthenticatedRequest[_]) => Option[Int]): Option[Int] = {
fold(authenticated)(unauthenticated)(request)
}
}
上面的代码编译。
然后我说:我应该将fold [T]参数化类型限制为Int和Option [Int],所以我补充说:
object ParFuncApply {
trait CanBeAuthenticatedRequest[A]
trait AuthenticatedRequest[A] extends CanBeAuthenticatedRequest[A]
trait UnauthenticatedRequest[A] extends CanBeAuthenticatedRequest[A]
sealed trait Helper[T]
object Helper {
implicit object FutureResultHelper extends Helper[Option[Int]]
implicit object ResultHelper extends Helper[Int]
}
private def fold[T: Helper](authenticated: (AuthenticatedRequest[_]) => T)
(unauthenticated: (UnauthenticatedRequest[_]) => T):
PartialFunction[CanBeAuthenticatedRequest[_], T] = {
case ar: AuthenticatedRequest[_] => authenticated(ar)
case ur: UnauthenticatedRequest[_] => unauthenticated(ur)
}
def apply(request: CanBeAuthenticatedRequest[_])
(authenticated: (AuthenticatedRequest[_]) => Int)
(unauthenticated: (UnauthenticatedRequest[_]) => Int): Int = {
fold(authenticated)(unauthenticated)(request)
}
def async(request: CanBeAuthenticatedRequest[_])
(authenticated: (AuthenticatedRequest[_]) => Option[Int])
(unauthenticated: (UnauthenticatedRequest[_]) => Option[Int]): Option[Int] = {
fold(authenticated)(unauthenticated)(request)
}
}
但是,如果我更改,此代码不再编译
fold(authenticated)(unauthenticated)(request)
到fold(authenticated)(unauthenticated).apply(request)
(我添加了一个显式调用apply())它编译。为什么会这样?对类的调用()和.apply()应该是相同的,不是吗?
编译器似乎要求将返回类型(Int或Option [Int])传递给PartialFunction而不是CanBeAuthenticatedRequest类型。
答案 0 :(得分:3)
因为您在`fold [T:Helper]'中定义了一个上下文,编译器将添加另一个参数列表。换句话说,上下文绑定只是语法糖:
private def fold[T](authenticated: (AuthenticatedRequest[_]) => T)
(unauthenticated: (UnauthenticatedRequest[_]) => T)
(implicit helper: Helper[T): PartialFunction[CanBeAuthenticatedRequest[_], T]
所以当你打电话时
fold(authenticated)(unauthenticated)(request)
编译器认为request
应该是一个明确指定的隐式Helper [T]。