首页 文章

斯卡拉:如何等待未来

提问于
浏览
0

在以下代码段中,方法 bookExists 调用方法 find 来确定由指定的id标识的书是否存在:

class BookStore {

  def find(id: String): Future[Option[Book]] = {
    // read from db
    ...
  }

  def bookExists(id: String): Boolean = {
    find(id).map {
      case Some(_) => true
      case _ => false
    }.recover {
      case e => false
    }
  }
}

问题是上面的类不能编译,因为我需要等到 Future 实际完成 . 我总是收到以下错误消息:

[error] /home/j3d/test/BookStore.scala:118: type mismatch;
[error]  found   : scala.concurrent.Future[Boolean]
[error]  required: Boolean
[error]         ).map {
[error]               ^

处理这种情况的正确方法是什么?

2 回答

  • 2

    除非您正在等待结果,否则您将此Future [Option [Book]]映射到Future [Boolean]类型的另一个未来 . 没有等待计算将在查找Future完成后发生(如果有的话) . 更改您的退货类型:

    def bookExists(id: String): Future[Boolean] = {   
        find(id).map { _ match {  // '_' in the map is a Option[Book] extracted from the Future[Option[Book]] find returns
            case Some(_) => true  // '_' in the match is Book extracted from the Option[Book] in the match statement
            case _ => false
          }.recover {
            case e => false
          }
        }
      }
    
  • 2

    通常你会返回 Future[Boolean] 因此推迟要求尽可能长的答案 .

    但是如果在答案可用之前阻止是很重要的,那么使用 scala.concurrent.Await (最好用 Try 包裹以捕获错误) .

相关问题