我有以下功能。
def get(id: Int): Future[Either[String, Item]] = {
request(RequestBuilding.Get(s"/log/$id")).flatMap { response =>
response.status match {
case OK => Unmarshal(response.entity).to[Item].map(Right(_))
case BadRequest => Future.successful(Left(s"Bad Request"))
case _ => Unmarshal(response.entity).to[String].flatMap { entity =>
val error = s"Request failed with status code ${response.status} and entity $entity"
Future.failed(new IOException(error))
}
}
}
}
我正在尝试调用此函数,但我不知道如何知道它是返回String还是Item。以下是我失败的尝试。
Client.get(1).onComplete { result =>
result match {
case Left(msg) => println(msg)
case Right(item) => // Do something
}
}
答案 0 :(得分:1)
onComplete
采用Try
类型的函数,因此您必须在Try
上进行双重匹配,并且在Either
成功的情况下
Client.get(1).onComplete {
case Success(either) => either match {
case Left(int) => int
case Right(string) => string
}
case Failure(f) => f
}
更容易映射未来:
Client.get(1).map {
case Left(msg) => println(msg)
case Right(item) => // Do something
}
如果您想要处理Failure
的{{1}}部分,请在对未来进行映射后使用onComplete
或recover
。