2016-12-11 7 views
4

私はこのような1コントローラのアクションを実装している:Scala Play 2.5フォームbindFromRequest:ここでHTTPリクエストを見つけることができませんか?

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") 
    ) 
    } 
    } 
} 
実装は上記のコンパイルエラーにつながる

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

:私はから2行目を変更した場合、

[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 

しかし、 〜

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

それはコンパイル...しかし、なぜですか?あなたはこのように、スコープのimplicit requestを必要とする

+0

要求は、暗黙のスコープであることが必要です。なければ、それはコンパイルされません。 – cchantep

答えて

5

Implicit Parametersです。要約:

暗黙のパラメータは、通常のパラメータまたは明示的なパラメータと同様に渡すことができます。暗黙のパラメータを明示的に指定しない場合、コンパイラはあなたに渡すことを試みます。インプリシットはさまざまな場所から来ることができます。よくある質問Where does Scala look for implicits?から:

  1. First look in current scope
    • Implicits defined in current scope
    • Explicit imports
    • wildcard imports
  2. Now look at associated types in
    • Companion objects of a type
    • Implicit scope of an argument’s type (2.9.1)
    • Implicit scope of type arguments (2.8.0)
    • Outer objects for nested types
    • Other dimensions

暗黙数1が優先下の番号2.

下のものよりもあなたの例ではimplicitとしてrequestをマークすることによって、あなたは、「現在のスコープで定義された暗黙の」宣言しています。 bindFormRequestはあなたに「尋ねる」ので、暗黙の要求が必要です。その署名を参照してください:

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

今、あなたがスコープ内にimplicit requestを持っていることを、コンパイラが自動的にbindFormRequerstに渡します。

私は冒頭で述べたように、あなたはまた、request明示的に渡すことができます。

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

を後者のケースでは、あなたが明らかに明示的requestを渡しているようimplicitとしてrequestを宣言する必要はありません。両方の変種は等しい。それはあなたが好むものはあなた次第です。

1
+1

これはもう少し前にやったPlayアプリのチュートリアルのコードです。私はまたあなたが見つけるかもしれないいくつかの困難をカバーするかもしれないブログ記事を書いた。それがあなたを助けてくれることを願っています。 – pedrorijo91

+0

はい、私はそれを得ました...しかし、言語的には、この場合要求のようなパラメータを暗黙的に修飾することはどういう意味ですか? –

関連する問題