如何使用函数返回值在scala中返回Future([A,B])?

时间:2016-02-21 18:49:11

标签: scala future either

我有以下功能。

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
        }
      }

1 个答案:

答案 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}}部分,请在对未来进行映射后使用onCompleterecover

相关问题