首页 文章

Future和Scala:数据类型不匹配

提问于
浏览
-1

我有下一个代码:

package controllers.usersPage

import play.api.mvc._
import play.api.libs.json._
import model.{User, Users, Patients, CObject}
import scala.concurrent.Future

import service.{UserService}

class allUsersToJSON() extends Controller {

def convertUsersToJsonOrig(lusers: Seq[User]): JsValue = {Json.toJson(
                                               lusers.map { u => Map("id" -> u.id, "firstName" -> u.firstName, "lastName" -> u.lastName, "email" -> u.email, "username" -> u.username, "password" -> u.password)}) }


def retAllUsers = Action { request =>
   Ok( Json.stringify(convertUsersToJsonOrig(Users.listAll)))
  }
}

但是,我收到了下一个错误:

$ compile
[info] Compiling 69 Scala sources and 3 Java sources to 
H:\project\target\scala-2.11\classes...
[error] H:\project\app\controllers\usersPage\retrieveAllUsersJSON.scala:29: type mismatch;
[error]  found   : scala.concurrent.Future[Seq[model.User]]
[error]  required: Seq[model.User]
[error]      Ok( Json.stringify(convertUsersToJsonOrig(Users.listAll)))
[error]                                                      ^
[warn] Class com.sun.tools.xjc.Options not found - continuing with a stub.
[warn] one warning found
[error] one error found
[error] (root/compile:compileIncremental) Compilation failed
[error] Total time: 7 s, completed Apr 17, 2017 10:51:11 AM

Users.listAll指令是Future,它将为我提供一个我需要转换为JSon的User对象列表 . 我看到这个命令给了我scala.concurrent.Future [Seq [model.User]]数据类型 . 如何从此命令获取Seq [model.user],以便在convertUsersToJsonOrig中使用它?谢谢

1 回答

  • 3

    看看这里处理期货玩具:https://www.playframework.com/documentation/2.5.x/ScalaAsync

    def retAllUsers = Action.async { request =>
      for {
        users <- Users.listAll
      } yield Ok( Json.stringify(convertUsersToJsonOrig(users)))
    }
    

    Action 需要 Request => Result . 虽然 Action.async 需要 Request => Future[Result] . 这允许您将未来的内容(使用map,flatMap和/或for-comprehension)转换为 Result 并将其提供给框架来处理 .

相关问题