2014-06-19 100 views
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

爲什麼不''.map(_。nonEmpty)'? –

回答

2

除非您正在等待結果,否則您將此Future [Option [Book]]映射到Future [Boolean]類型的另一個未來。如果沒有等待,計算將發生在查找未來完成後(如果有的話)。更改您的退貨類型:

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以捕獲錯誤)。