【问题标题】:Scala: "required: scala.concurrent.Future[?]"Scala:“必需:scala.concurrent.Future[?]”
【发布时间】:2014-06-09 05:06:31
【问题描述】:

编辑

仍然没有找到解决方案,所以我最终创建了两个 someFuture 方法。一个返回未来,一个不返回(让otherFuture 编译)


我正在尝试返回 Future[Option[JsObject]],但不断收到此错误:

required: scala.concurrent.Future[?]

我在做什么

def someFuture:Future[Option[JsObject]] =
  Future {
    Option(JsObject())
  }

def otherFuture:Future[Option[JsObject]] =
  Future {
    Option(JsObject(
      someFuture.flatMap(_.get)
    ))
  }

// get error here
found   : JsObject
[error]  required: scala.concurrent.Future[?]

如何返回 JsObject 而不会出错?

【问题讨论】:

    标签: scala


    【解决方案1】:

    问题在于 someFuture.flatMap(_.get) 无法编译——您需要提供一个函数,该函数接受 JsObject 并返回 Future[Whatever] 以在 someFuture 上使用 flatMap

    你可能想要这样的东西:

    def otherFuture: Future[Option[JsObject]] = someFuture.map { opt =>
      Option(JsObject(opt.get))
    }
    

    不过,如果您只是像这样调用.get,则没有任何理由使用Option,所以以下可能会更好:

    def otherFuture: Future[Option[JsObject]] = someFuture.map(_.map(JsObject(_)))
    

    现在如果未来满足于非空选项,选项的内容将被包裹在另一层JsObject中,这似乎是你的目标?

    请注意,如果您使用 Option 表示失败,则可能需要考虑使用 Future 中内置的失败处理。

    【讨论】:

    • 这次在“JsObject”处出现不同的错误:overloaded method value apply with alternatives: [error] (fields: Map[String,spray.json.JsValue])spray.json.JsObject <and> [error] (members: List[(String, spray.json.JsValue)])spray.json.JsObject <and> [error] (members: (String, spray.json.JsValue)*)spray.json.JsObject [error] cannot be applied to (spray.json.JsValue)
    • 我只是关注您对JsObject 的使用,但它不会有一个构造函数采用另一个JsObject 是有道理的。可以用JsObject("someKey" -> _)吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-06
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多