Scala + Play Framework:需要动作构图说明

时间:2012-10-21 11:24:42

标签: scala playframework-2.0

这是从Play Framework附带的示例中采取的动作组合

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

因此,Security.Authenticated需要username: RequestHeader => Option[String]onAuthorized: RequestHeader=>SimpleResult,第二组代价需要String => Action[A]

然后在控制器中我有:

def index = isAuthenticated { ...code }}  

上面的代码是这样的,所以我假设这是f函数=> String => Request[AnyContent] => Result。现在,我不明白的是这里真正发生的事情。我不是在谈论User.findByEmail....,我在谈论username => _ => ...。如果我直接调用它,这个函数的签名会是什么样的?

username => _ =>
    User.findByEmail(username).map { user =>
      Ok(
        html.dashboard(
          Project.findInvolving(username), 
          Task.findTodoInvolving(username), 
          user
        )
      )
    }.getOrElse(Forbidden)  

如果有def isAuthenticated(f: => Request[AnyContent] => Result)我知道如何使用它,我就明白了。但额外的“数据”让我感到困惑。

更新:

我想我找到了一些东西:

def f2: String => Int => List[Char] = x => _ => x.toList  

这将被称为:

f2("Andrew")(2) //there can be anything replacing 2 because I don't have access to it anyway  

所以上面提到的函数主要是:

def f: => String => Request[AnyContent] => Result = username => _ => User.find.....  

我是对的吗? 我得到了“此处允许的名字参数错误”。

如果他们不使用第二个参数,为什么他们使用String => Request => Result而不仅仅是String => Result

2 个答案:

答案 0 :(得分:1)

该函数定义实际上是一个curried函数定义。

String => Request => Result实际上意味着:f(s:String):(r:Request)=>Result即一个函数,它接受一个String并返回一个函数,它接受一个Request并返回一个Result。

查看“调整您的功能”部分:http://danielwestheide.com/blog/2013/01/30/the-neophytes-guide-to-scala-part-11-currying-and-partially-applied-functions.html

答案 1 :(得分:0)

对我而言,https://github.com/mariussoutier/PlayBasics/tree/master/play-2.2-migration的例子非常具有启发性。

相关问题