-1

这是我的代码:

package controllers

import play.api._
import play.api.mvc._
import play.api.data.Form
import play.api.data.Forms.tuple
import play.api.data.Forms.text


object Application extends Controller {

def index = Action {
  Ok(views.html.index("Your new application is ready."))
}

val form = Form(
tuple(
  "name" -> text,
  "address" -> text,
  "x_card_num" -> text
 )
)

def payment = Action { implicit request =>
  def values = form.bindFromRequest.data
  def name = values("name")

  //val card_num = ""
  //values.isDefinedAt("x_card_num")
  if (values.get("x_card_num") == None)       {
      val card_num = "test"
  }   else    {
    //def card_num = values("x_card_num")
    val card_num = "test2"
}

//val card_num = "test"
Ok(views.html.payment("testing",name,card_num))
}

}

它不起作用。它只是为了完全跳过 if (values.get("x_card_num") == None) 和 else 语句,并且 card_num 最终为空字符串,如 if else 语句之前定义的那样。

为什么它会完全忽略 if else 语句?

以及如何检查数组“值”中是否存在键?

4

1 回答 1

4

The problem here is that you are shadowing the outer scope. That is, you are declaring more than one value called card_num.

if (values.get("x_card_num") == None) {     
   val card_num = "test"   
// ^^^
// this is a new variable declaration in a different scope
} 
else  
  val card_num = "test2"

In scala, everything is an expression, so you can simply do this:

val card_num = if (values.get("x_card_num") == None)  "test" else { ... }

That is, the if-block itself evaluates to a value (as long as there is an else)

the other option is to use variables as opposed to values, but this is not idiomatic (you should avoid vars):

var card_num = null
if ( .. ) 
   card_num = "test"
// ^^^
// Notice no val or var here

You could use isDefinedAt to simplify the test

val cardNum = if (values isDefinedAt "x_card_num") "test2" else "test"
于 2012-06-27T17:19:45.303 回答