在以下代码段中,方法 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 回答
除非您正在等待结果,否则您将此Future [Option [Book]]映射到Future [Boolean]类型的另一个未来 . 没有等待计算将在查找Future完成后发生(如果有的话) . 更改您的退货类型:
通常你会返回
Future[Boolean]
因此推迟要求尽可能长的答案 .但是如果在答案可用之前阻止是很重要的,那么使用
scala.concurrent.Await
(最好用Try
包裹以捕获错误) .