【问题标题】:type mismatch scala.concurrent.Future with Slick & Play Framework类型不匹配 scala.concurrent.Future 与 Slick & Play 框架
【发布时间】:2016-07-28 02:47:56
【问题描述】:

你好,

    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

还有这个:

谁能解释为什么会出现这个错误并给我一些提示来解决它?

谢谢

【问题讨论】:

  • 不要发文字截图,用文字代替...
  • 我尝试在代码中将 '(' 加粗,但在 Stackoverflow 中是不可接受的!

标签: scala web playframework functional-programming slick


【解决方案1】:

您的Message.getMessages 似乎返回一个Future[Something],这反过来又使您的整个match 块尝试在Success 情况下返回Future[Result],在Failure 情况下返回Result

您应该尝试以下类似的方法(注意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"
        ))))
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多