The following function should get a code block execute it and return future with corresponding message response. I get compilation error says: Required: Future[S_] Found: String, can someone explain why?
def withTransaction(blockOfCode: => Future[User])(implicit transaction: Transaction[User]): Future[String] = Future {
println("WithTransaction called...")
blockOfCode.flatMap(_ => {
transaction.commit()
"Success"
}).recover { // here is the error
transaction.rollback()
"Failed"
}
}
Future#recover expects a partial function
def recover[U >: T](pf: PartialFunction[Throwable, U])(implicit executor: ExecutionContext): Future[U] =
which can be expressed using curly brackets and case syntax like so
{ case e => expression }
however since e is not used we might as well use discarded parameter function syntax, as per jwvh's comment,
_ => expression
In your particular case it does not really matter which one you choose, but in general partial function would allow you to, say, have different types of recovery mechanisms per different types of error
{
case e: SocketTimeoutException => // recovery mechanism A
case e: ArithmeticException => // recovery mechanism B
case ...
}
Furthermore you likely need map instead of flatMap because you are mapping to "Success" instead of Future("Success"). Consider the difference between
Future(42).map(_ => "hello") // ok
Future(42).flatMap(_ => "hello") // error
Future(42).flatMap(_ => Future("hello")) // ok
Putting it together try
def withTransaction(
blockOfCode: => Future[User]
)(implicit transaction: Transaction[User]): Future[String] = {
blockOfCode
.map { _ =>
transaction.commit()
"Success"
}.recover { _ =>
transaction.rollback()
"Failed"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With