Scala中方法参数中的多个连续胖箭头是什么意思?

时间:2012-12-23 17:40:28

标签: scala playframework playframework-2.0

我知道方法可以有这样的代码:

def m(p1:Int => Int) ...

这意味着此方法采用函数p1返回Int

但是在浏览Play时!框架代码我找到了一个具有难以理解的方法的特征:

trait Secured {

  def username(request: RequestHeader) = request.session.get(Security.username)

  def onUnauthorized(request: RequestHeader) = Results.Redirect(routes.Auth.login)

  def withAuth(f: => String => Request[AnyContent] => Result) = {
    Security.Authenticated(username, onUnauthorized) { user =>
      Action(request => f(user)(request))
    }
  }

  /**
   * This method shows how you could wrap the withAuth method to also fetch your user
   * You will need to implement UserDAO.findOneByUsername
   */
  def withUser(f: User => Request[AnyContent] => Result) = withAuth { username => implicit request =>
    UserDAO.findOneByUsername(username).map { user =>
      f(user)(request)
    }.getOrElse(onUnauthorized(request))
  }
}

Play! Scala Security

f: User => Request[AnyContent] => Result是什么意思?乍一看,它看起来像一个返回Request类型的函数r的方法; r然后返回Result

这是正确的假设吗?

2 个答案:

答案 0 :(得分:16)

  

f:User =>请求[AnyContent] =>结果意味着?乍一看,它看起来像一个返回Request类型函数r的方法;然后r返回一个结果。

f会返回Request[AnyContent] => Result类型的函数,即一个取Request[AnyContent]并返回Result的函数。

换句话说,f是一个curried函数。您可以将其称为f(user)(request)以取回Result

答案 1 :(得分:1)

def withAuth(f: => String => Request[AnyContent] => Result)表示f是一个名字参数,您可以这样编写:

withAuth {
  logger.info("Here we go")
  ...
  chooseTheAction("list")
}

其中chooseTheAction获取String并返回执行请求的函数Request[AnyContent] => Result