需要以下scala片段的简单英语翻译

cri*_*ium 12 scala

我是scala和playframework的新手.有人可以将下面的以下片段翻译成普通英语吗?对于上下文,可在此处找到:http://www.playframework.org/documentation/2.0.4/ScalaSecurity

/**
 * 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))
}
Run Code Online (Sandbox Code Playgroud)

huy*_*hjl 22

第1部分:首先让我们解决curried语法:

withUser是一种采用f类型的curried函数的方法User => Request[AnyContent] => Result.它接受一个User对象并返回另一个接受a Request并返回a的函数Result.打破它,如果f是那个功能那么:

val g = f(user) // g is a function
val result = g(request) // returns a result
// same as:
val result = f(user)(request)
Run Code Online (Sandbox Code Playgroud)

实际上f,就像一个函数,它接受两个参数但不是叫f(a, b)你调用f(a)(b).

withAuth也是一种采用curry函数的方法.它的类型几乎相同withUser.

第2部分:现在如何使用这些方法:

正如解释在这里,玩耍,你告诉它如何改造定义应用程序逻辑Request的对象为Result对象.

withAuth是一个帮助函数,负责为您进行身份验证,并方便地检索用户名.所以你这样使用它:

def index = withAuth { username => implicit request =>
  Ok(html.index(username))
}
Run Code Online (Sandbox Code Playgroud)

它返回一个带a Request和返回a 的函数Result,这就是播放所需要的.但它需要的是一个curried函数(需要用户名)并返回一个函数(接受请求).请求参数标记为隐式,因此可以隐式传递给需要隐式请求参数的任何函数/方法调用.出于解释的目的,只需忽略implicit关键字.

第3部分:翻译 withUser

好吧,它的签名类似于,withAuth并且目标是以相同的方式使用它,除了第一个参数将是a User而不是a String.所以它必须采取User => Request => Result.请求特征采用类型参数,该参数指示其内容的类型.在这里AnyContent.所以参数的正确类型withUserUser => Request[AnyContent] => Result.这意味着您将能够像这样使用它:

withUser { user => implicit request =>
  // do something with user and request to return a result
}
Run Code Online (Sandbox Code Playgroud)

如果你看一下withUser它的定义,它只需要调用withAuth:

def withUser(f: User => Request[AnyContent] => Result) = withAuth { 
  // ...
}
Run Code Online (Sandbox Code Playgroud)

因此它将返回相同的类型,withAuth这意味着它将返回一个将a Request变为a 的函数Result(参见上面的第2部分).这意味着我们可以像这样使用它:

def index = withUser { user => implicit request => 
  Ok(html.index(user))
}
Run Code Online (Sandbox Code Playgroud)

作为参数传递的withAuth是一个curried函数.我介绍了中间体,val以便您可以遵循以下类型:

username => // first param is the username as a String
  implicit request => // second param is the request
    // here we have to return a Result...
    // we lookup the user - we may not have one:
    val userOption: Option[User] = UserDAO.findOneByUsername(username)
    // f is the code block that will be provided inside withUser { f }
    // Part 1 explains the f(user)(request) syntax
    // We call f to get a result, in the context of the Option monad
    val resultOption: Option[Result] = userOption.map(user => f(user)(request))
    // if we have a result, return it; otherwise return an error.
    resultOption.getOrElse(onUnauthorized(request))
Run Code Online (Sandbox Code Playgroud)