Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a Future[T] can I write function with onComplete callback which returns T?

Tags:

scala

I have this method:

def findById(id: String): Customer = {
     (new CustomerDaoEs).retrieve(Id[Customer](id)) onComplete {
      case Success(customer) => customer
      case Failure(t) => {
        throw new InvalidIdException(id.toString, "customer")
      }
    }
  }

Of course, the issue is that this returns Unit instead of Customer... So basically onComplete does not really behave like pattern matching.

Is there any way to keep returning Customer (or Option[Customer]) and make this work nice (I mean to keep this onComplete clean structure)?

like image 812
Cristian Boariu Avatar asked Sep 02 '26 08:09

Cristian Boariu


1 Answers

You could change exception using recover method:

def findById(id: String): Future[Customer] = {
  (new CustomerDaoEs).retrieve(Id[Customer](id)).recover{ case _ => throw new InvalidIdException(id.toString, "customer") }
}

Then you could use your method like this:

val customer = Await.result(findById("cust_id"), 5.seconds)

Alternatively you could replace exception with None:

def findById(id: String): Future[Option[Customer]] = {
  (new CustomerDaoEs).
    retrieve(Id[Customer](id)).
    map{ Some(_) }.
    recover{ case _ => None }
}
like image 75
senia Avatar answered Sep 05 '26 16:09

senia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!