【问题标题】:Scala type mismatch: found Future[MyType] required Future[Option[MyType]]Scala 类型不匹配:发现 Future[MyType] required Future[Option[MyType]]
【发布时间】:2018-05-01 23:53:25
【问题描述】:

我从 API 获得了 Future[MyType]。如何将Future[MyType] 转换为Future[Option[MyType]]

def getApiKey(id: String): Future[Option[MyType]] = Future {
  val g: Future[Option[MyType]] = getID(id) // error mismatch
  g
}

def getID(id: String): Future[MyType] = {
  //return Future[MyType]
}

【问题讨论】:

  • 已尝试但 API 返回 Future[MyType] 类型但所需类型是 Future[Option[MyType]] 这就是为什么要转换。

标签: scala


【解决方案1】:

使用map:

def getApiKey(id: String): Future[Option[MyType]] = {
  getID(id).map(Option(_))
}

【讨论】:

  • 完美,谢谢。我正在编写一个小服务器应用程序从 API 获取数据发送回客户端。但是在 GET 请求查询中获取 nil 数据成功生成。未来有问题吗?我应该设置睡眠时间吗?
猜你喜欢
  • 1970-01-01
  • 2020-10-17
  • 1970-01-01
  • 2016-11-08
  • 1970-01-01
  • 2015-11-03
  • 1970-01-01
  • 2017-09-20
  • 2015-10-09
相关资源
最近更新 更多