繁体   English   中英

处理Scala期货

[英]Handling Scala Futures

我正在编写Scala代码,以检查zip文件是否在Amazon S3上的某个位置可用。 如果是,我想返回路径; 如果不是,我想创建它, 然后返回路径。 答案是相同的(假设没有例外)。

我正在将Rhinofly play-s3库用于我的S3抽象,但是我认为这不太相关。 该库确实使用了Scala Future ,这就是这里的重点。 我的问题是Scala不喜欢在开始不可用时创建zip的方法的返回类型。

这是我的代码:

def zip(key: String): Future[String] = {
    val zipFileName = key + ".zip"
    val zipFile = bucket get zipFileName //Returns a Future[BucketFile] or S3Exception
    zipFile.map(bucketFile => bucketFile.name).recover {
      case S3Exception(status, code, message, originalXml) => createZip(key)
      case _ => "Who cares for now?"
    }
}

假设路径愉快,并且唯一可能发生的异常是没有现有zip的404。

同时, createZip(key)返回Future[String]

我得到的编译错误是这样的:

type mismatch;
 found   : scala.concurrent.Future[String]
 required: String

所以我想zip方法返回Future[String] 我以为从zipFilebucketFile.namemap返回Future[String] ,而createZip肯定返回Future[String]

所以有什么问题? 为什么String是必需的返回类型? 如何重写其中一个或两个方法来实现我的目标?

recover会将Future恢复为默认值。 在这种情况下, String 你想要的是recoverWith恢复Future另一个 Future

def zip(key: String): Future[String] = {
    val zipFileName = key + ".zip"
    val zipFile = bucket get zipFileName //Returns a Future[BucketFile] or S3Exception
    zipFile.map(bucketFile => bucketFile.name).recoverWith {
      case S3Exception(status, code, message, originalXml) => createZip(key)
    }
}

您具有异步恢复(即,您的恢复返回的是Future[String]而不是String 。请使用recoverWith ,它允许您使用创建Future的回调。请注意,“谁在乎现在”需要升级为通过调用Future.success("Who cares for now") Future ,否则您可以让错误Future.success("Who cares for now")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM