5

我有一个这样实现的控制器操作:

def doChangePassword = deadbolt.Restrict(List(Array(Application.USER_ROLE_KEY)))() 
{ request => // <<<<<<<<<<<< here is the request 
  Future {
    val context = JavaHelpers.createJavaContext(request)
    com.feth.play.module.pa.controllers.AuthenticateBase.noCache(context.response())

    val filledForm = Account.PasswordChangeForm.bindFromRequest
    // compilation error here, it can't see the request ^^^^^^^

    if (filledForm.hasErrors) {
      // User did not select whether to link or not link
      BadRequest(views.html.account.password_change(userService, filledForm))
    } else {
      val Some(user: UserRow) = userService.getUser(context.session)
      val newPassword = filledForm.get.password
      userService.changePassword(user, new MyUsernamePasswordAuthUser(newPassword), true)
      Redirect(routes.Application.profile).flashing(
        Application.FLASH_MESSAGE_KEY -> messagesApi.preferred(request)("playauthenticate.change_password.success")
      )
    }
  }
}

上面的实现导致编译错误:

[error] /home/bravegag/code/play-authenticate-usage-scala/app/controllers/Account.scala:74: Cannot find any HTTP Request here
[error]         val filledForm =  Account.PasswordChangeForm.bindFromRequest
[error]                                                     ^
[error] one error found

但是,如果我将第 2 行更改为:

{ request => // <<<<<<<<<<<< here is the request 

{ implicit request => // <<<<<<<<<<<< here is the request 

然后它编译...但是为什么呢?

4

2 回答 2

8

您正在寻找的是隐式参数。简而言之:

隐式参数可以像常规或显式参数一样传递。如果您没有显式提供隐式参数,那么编译器将尝试为您传递一个。隐式可以来自不同的地方。来自常见问题解答Scala 在哪里寻找隐式?

  1. 首先查看当前范围
    • 当前范围内定义的隐式
    • 显式导入
    • 通配符导入
  2. 现在查看关联类型
    • 类型的伴随对象
    • 参数类型的隐式范围 (2.9.1)
    • 类型参数的隐式范围 (2.8.0)
    • 嵌套类型的外部对象
    • 其他尺寸

第 1 项下的隐含优先于第 2 项下的隐含。

通过在您的示例中进行标记requestimplicit您正在声明“在当前范围内隐式定义”。您需要有一个隐式请求,因为bindFormRequest“要求”您通过一个。查看其签名:

bindFromRequest()(implicit request: Request[_]): Form[T]

现在你有了一个implicit requestin 范围,编译器会自动将它传递给bindFormRequerst.

正如我在开头提到的,您也可以request显式传递:

val filledForm = Account.PasswordChangeForm.bindFromRequest()(request)

在后一种情况下,无需声明requestimplicit因为您显然是request明确传递的。两种变体是相等的。这取决于你喜欢哪一个。

于 2016-12-12T08:21:17.483 回答
2

你需要一个implicit request范围内,像这样:https ://github.com/pedrorijo91/play-slick3-steps/blob/master/app/controllers/ApplicationController.scala#L11

于 2016-12-11T21:25:50.370 回答