在Play中使用Scala Trait时类型不匹配?

时间:2012-03-01 10:20:29

标签: scala playframework

使用Play!框架1.2.4。我有一个很好的特性来检查API密钥和HTTPS,但如果我想访问与该密钥关联的帐户并在我的控制器中引用它,它会抛出type mismatch; found : java.lang.Object required: Long

所以这是我的API控制器(不完整):

object API extends Controller with Squeryl with SecureAPI {

  import views.API._

  def job(param:String) = {


    val Job = models.Job
    param match {
      case "new"    => Job.createFromParams(params,thisAccount) //thisAccount comes from the trait
      case "update" =>
      case "get"    =>
      case "list"   =>
    }
  }

}

和安全特性:

trait SecureAPI {
  self:Controller =>

  @Before
  def checkSecurity(key:String) = {
      if(!self.request.secure.booleanValue) {
          Redirect("https://" + request.host + request.url);
      } else {
          models.Account.getByKey(key) match {
            case Some(account)  =>  {
              renderArgs += "account" -> account.id
              Continue
            }
            case _  =>  Forbidden("Key is not authorized.")
          }
      }
  }

  def thisAccount = renderArgs("account").get
}

我如何正确访问thisAccount?感谢

1 个答案:

答案 0 :(得分:2)

您的问题很简单,renderArgs仅被声明为从其Object电话中返回get(这很公平,因为它几乎可以是任何事情)。

因此,thisAccount方法的推断类型为() => Object

你需要将返回的类型强制转换为Long,类似于(尽管可能有一些错误检查):

def thisAccount = renderArgs("account").get.asInstanceOf[Long]