使用替代方法重载方法值async:

时间:2015-04-16 07:34:34

标签: scala playframework reactivemongo

当我有以下代码时,一切都编译得很好。

 def create(name: String, age: Int) = Action.async {
    val json = Json.obj(
      "name" -> name,
      "age" -> age,
      "created" -> new java.util.Date().getTime())

    collection.insert(json).map(lastError =>
      Ok("Mongo LastError: %s".format(lastError)))
  }

但是当将内容提取到另一个方法时如下

 def create(name: String, age: Int) = Action.async {
   createPerson(name,age)
 }

  def createPerson(name: String, age: Int) = Action.async {
    val json = Json.obj(
      "name" -> name,
      "age" -> age,
      "created" -> new java.util.Date().getTime())

    collection.insert(json).map(lastError =>
      Ok("Mongo LastError: %s".format(lastError)))
  }

它给出错误

[error] /media/pubudu/NTFSPartition/projects/catnet/data-collector-backend/app/controllers/Application.scala:50: overloaded method value async with alternatives:
[error]   [A](bodyParser: play.api.mvc.BodyParser[A])(block: play.api.mvc.Request[A] => scala.concurrent.Future[play.api.mvc.Result])play.api.mvc.Action[A] <and>
[error]   (block: play.api.mvc.Request[play.api.mvc.AnyContent] => scala.concurrent.Future[play.api.mvc.Result])play.api.mvc.Action[play.api.mvc.AnyContent] <and>
[error]   (block: => scala.concurrent.Future[play.api.mvc.Result])play.api.mvc.Action[play.api.mvc.AnyContent]
[error]  cannot be applied to (play.api.mvc.Action[play.api.mvc.AnyContent])
[error]   def create(name: String, age: Int) = Action.async {

这两个代码部分做同样的事情吗?如果没有,如何在不收到错误的情况下提取方法的内容?我想要做的是从两个不同的地方调用提取的方法。

1 个答案:

答案 0 :(得分:4)

create方法要求返回类型为Future[Result],但调用createPerson会返回Action[AnyContent]。您可以通过进行以下更改来更正它:

def create(name: String, age: Int) = Action.async {
   createPerson(name,age).map(lastError =>
      Ok("Mongo LastError: %s".format(lastError)))
 }

  def createPerson(name: String, age: Int):Future[String] = {
    val json = Json.obj(
      "name" -> name,
      "age" -> age,
      "created" -> new java.util.Date().getTime())

    collection.insert(json)
  }