类型不匹配scala.concurrent.Future与Slick&玩框架

时间:2016-04-07 09:48:01

标签: scala web playframework functional-programming slick

你好,

    def getMessages(code:String,offset:Option[Int]) = Action.async(parse.json){request =>

    val forPC = (request.body \ "forPC").asOpt[Boolean]

    Talk.findByCode(code).map(_ match{
        case Success(talk) =>
            val talkId = talk.id
            Message.getMessages(talkId=talkId,offset=offset.getOrElse(0), forPC ).map(_ match {
                case Seq(Tables.Messages) => Ok("Cool")
                case    _ => Ok("No")
            })
        case Failure(e) =>
            Logger.error(e.getMessage)
            NotAcceptable(Json.toJson(Map(
                "error" -> "failed"
            )))
    })

在模型中我有:

// talks by Code
  def findByCode(code: String, conferenceid : Int) = {
    val query = talks.filter(talk => talk.conferenceId === conferenceid && talk.code === code)
    db.run(query.result.head.asTry)
  }


    def getMessages(talkId:Int ,offset:Int, forPC: Option[Boolean]) = {
    val forPCVal = forPC.getOrElse(false)
    //ordering by talkId because it's faster than timestamp
    val query = messages.filter(msg => msg.talkId === talkId && msg.forpc === forPCVal ).sortBy(_.idmessage.desc).drop(offset).take(10).result
    db.run(query)
}

所以Play正在等待Result(Action),并显示以下错误:

type mismatch;
 found   : scala.concurrent.Future[play.api.mvc.Result]
 required: play.api.mvc.Result

和此:

enter image description here

任何人都可以解释为什么会出现这个错误并给我一些提示来解决它吗?

谢谢

1 个答案:

答案 0 :(得分:0)

您的Message.getMessages似乎返回Future[Something],这反过来会让您的整个match阻止尝试在Future[Result]案例中返回Success Result案例中的Failure

你应该尝试以下内容(注意flatMap,确保你最终得到Future[Result]而不是Future[Future[Result]]

Talk.findByCode(code).flatMap(_ match{
    case Success(talk) =>
        val talkId = talk.id
        Message.getMessages(talkId=talkId,offset=offset.getOrElse(0), forPC ).map(_ match {
            case Seq(Tables.Messages) => Ok("Cool")
            case    _ => Ok("No")
        })
    case Failure(e) =>
        Logger.error(e.getMessage)
        Future.successful(NotAcceptable(Json.toJson(Map(
            "error" -> "failed"
        ))))
})