0

パターンマッチングでセッション値を使用したいのですが、request.get( "profileType")がOption [String]を返すため、コードのようにパターンマッチングで使用できません。これが私のコードスニペットです。

def editorProfile = Action { implicit request =>
request.session.get("profileType").toString() match {
  case "editor" => {
      request.session.get("userEmail").map {
        userEmail => Ok(html.profile.editorProfile("my profile"))
      }.getOrElse {
        Unauthorized(html.error("Not logged in"))
      }
  }
 }
}

エラーは次のとおりです。

[MatchError: Some(editor) (of class java.lang.String)]

私の質問はです。パターンマッチングでsession.getからこのSome(editor)を使用するにはどうすればよいですか?

4

2 に答える 2

2

同様のタイプのチェックをさらに追加するとスケーリングが容易になる可能性があるため、理解のためにforを使用することをお勧めします。

val email = for {
  profileType <- request.session.get("profileType") if profileType == "editor"
  userEmail <- request.session.get("userEmail")
} yield userEmail

// email is of type Option[String] now, so we do the matching accordingly

email match {
  case m: Some => Ok(html.profile.editorProfile("my profile"))
  case None => Unauthorized(html.error("Not logged in or not an editor."))
}

もちろん、これらすべてをさらに簡潔に書くこともできますが、初心者としては、より明確にすることを損なうことはありません。

添加:

後でメールアドレスを使用する場合は、次のように変更できます。

email match {
  case Some(address) => Ok(html.profile.editorProfileWithEmail("my profile", address))
  case None => Unauthorized(html.error("Not logged in or not an editor."))
}
于 2013-03-15T12:01:39.457 に答える
2

あなたは呼び出しtoStringOption[String]取得します"Some(editor)"。代わりに、これに一致する必要があります。

request.session.get("profileType") match {
  case Some("editor") => { /* your code */}
  case _ => /* something else */ 
}

デフォルトのケースを追加したことに注意してください_ =>。これがないと、「profileType」属性が含まれていないか、属性に別の値があるMatchErrorかどうかを確認できます。session

于 2013-03-15T10:59:40.777 に答える