播放Scala框架:类型不匹配scala.concurrent.Future [Object] [error] required:scala.concurrent.Future [play.api.mvc.Result]

时间:2016-03-30 08:54:33

标签: scala playframework

我有一个我无法解决的编译错误。这是一个将新患者添加到mongo中的动作,如果他还没有进入数据库的话。首先是模型:

 case class PatientData(id : String)

 object PatientData {
    implicit val PatientDataFormat = Json.format[PatientData]
  }

用mongo搜索病人的功能:

 def findPatientById(mode : String, id : String) : Future[Option[PatientData]] = {
    val collection = getPatientCollection(mode)
    collection.find(Json.obj("id" -> id)).one[PatientData]
  }

播放动作:

def create(patientId: String) = Action.async(parse.json) { request =>
    val token = "dummy"
    isAuthorized(token) match { // always return Some(thing) 
      case None => Future.successful(Unauthorized("Invalid token " + token))
      case Some(_) =>
        request.body.validate[PatientData] map { 
          patientData =>
          findPatientById(mode,patientId) map { finded =>
            finded match {
              case Some(_) => Future.successful(NotAcceptable("The patient is already exist."))
              case None =>
                Logger.info("Create the patient .. ")
                Future.successful(Created)
            }
          }
        } getOrElse {
          Future.successful(BadRequest)
        }
    }

我知道我可以使用函数Await.result中的findPatientById调用来解决此问题,但我想避免使用此解决方案并让Future完成其工作。问题是我收到了编译错误:

[error] /home/afk/git/bioserenity/bioserenity-backend/app/controllers/MedataController.scala:90: type mismatch;
[error]  found   : scala.concurrent.Future[Object]
[error]  required: scala.concurrent.Future[play.api.mvc.Result]
[error]         } getOrElse {
[error]           ^
[error] one error found
[error] (compile:compileIncremental) Compilation failed

有人有想法解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

您应该尝试使用

findPatientById(mode,patientId) flatMap { ...

而不是原始线。在这里,map调用被flatMap替换,以便该代码块返回的实例为Future[Something]而不是Future[Future[Something]]