斯卡拉:如何等待未来

时间:2014-06-19 17:10:42

标签: scala future

在以下代码段中,方法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 个答案:

答案 0 :(得分:2)

通常你会返回Future[Boolean],因此要求尽可能长时间地得到答案。

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

答案 1 :(得分: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
      }
    }
  }