处理Scala中的未来[Either]类型

时间:2015-10-24 13:05:39

标签: scala future either

我有点难以实现这种结构化。这是我正在尝试做的事情:

def checkResultAndFetchUser(result: WriteResult, encryptedEmail: String): Future[Either[ServiceError, User]] = Future {
  if (result.code contains 11000)
    Left(ServiceError("Email already exists"))
  else if (result.hasErrors)
    Left(ServiceError(result.writeErrors.map(_.errmsg).toString))
  else
    userByEmail(encryptedEmail).map(user =>
      user
    ).recover {
      case NonFatal(ex) => Left(ServiceError(ex.getMessage))
    }
}

checkResultAndFetchUser(
  await(userCollection.insert(encryptedUser)), encryptedUser.email
)

我期待checkResultAndFetchUser返回Future[Either[ServiceError, User]],但我看到以下编译器失败:

Error:(155, 28) type mismatch;
 found   : scala.concurrent.Future[Either[DBService.this.ServiceError,com.inland.model.User]]
 required: Either[DBService.this.ServiceError,com.inland.model.User]
Error occurred in an application involving default arguments.
    checkResultAndFetchUser(
                           ^
Error:(150, 19) type mismatch;
 found   : scala.concurrent.Future[Either[DBService.this.ServiceError,com.inland.model.User]]
 required: Either[DBService.this.ServiceError,com.inland.model.User]
        ).recover {
                  ^

userByEmail(encryptedEmail)方法给了我一个Future[Either[ServiceError, User]],正如我所期望的那样,但为什么以及在哪里出现问题?

编辑:我找到了解决方案:

def checkResultAndFetchUser(result: WriteResult, encryptedEmail: String): Future[Either[ServiceError, User]] = {
  if (result.code contains 11000)
    Future(Left(ServiceError("Email already exists")))
  else if (result.hasErrors)
    Future(Left(ServiceError(result.writeErrors.map(_.errmsg).toString)))
  else
    userByEmail(encryptedEmail)
}

await(checkResultAndFetchUser(
  await(userCollection.insert(encryptedUser)), encryptedUser.email
))

好吗?我的意思是,实现是安全的,因为我使用局部变量来返回Future

1 个答案:

答案 0 :(得分:2)

您的代码在产生预期结果的意义上是可以的。然而正如@Łukasz在评论中提到的那样,这样做有点浪费。

原因是无论何时像这样实例化Future,都会生成一个需要在某些ExecutionContext上进行调度的新任务。通常只要你需要在Future中包装已计算的结果(或者如果计算速度非常快),最好使用Future.successful以避免开销。

以下是我将如何修改checkResultAndFetchUser函数:

def checkResultAndFetchUser(result: WriteResult, encryptedEmail: String): Future[Either[ServiceError, User]] = {
  if (result.code contains 11000)
    Future.successful(Left(ServiceError("Email already exists")))
  else if (result.hasErrors)
    Future.successful(Left(ServiceError(result.writeErrors.map(_.errmsg).toString)))
  else
    userByEmail(encryptedEmail)
}
相关问题