Scala: How to wait for a Future -
in next code snippet, method bookexists
invokes method find
determine whether book identified specified id exists:
class bookstore { def find(id: string): future[option[book]] = { // read db ... } def bookexists(id: string): boolean = { find(id).map { case some(_) => true case _ => false }.recover { case e => false } } }
the problem class above doesn't compile because need wait until future
completes. next error message:
[error] /home/j3d/test/bookstore.scala:118: type mismatch; [error] found : scala.concurrent.future[boolean] [error] required: boolean [error] ).map { [error] ^
what's right way handle case?
unless awaiting result mapping future[option[book]] future of type future[boolean]. without await computation take place after find future completes (if @ all). alter homecoming type:
def bookexists(id: string): future[boolean] = { find(id).map { _ match { // '_' in map option[book] extracted future[option[book]] find returns case some(_) => true // '_' in match book extracted option[book] in match statement case _ => false }.recover { case e => false } } }
scala future
No comments:
Post a Comment