Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala compilation error: Required: Future[S_] Found: String

Tags:

scala

future

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"
  }
}
like image 982
ALjazzguitar Avatar asked May 19 '26 08:05

ALjazzguitar


1 Answers

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"
    }
}
like image 150
Mario Galic Avatar answered May 20 '26 22:05

Mario Galic